FE/JavaScript

[JS] 자바스크립트 기본 문법

셰욘 2024. 12. 16. 10:49
728x90

변수와 상수 (var, let, const)

변수 다루는 법

// 변수 만드는 법
let 변수;

// 변수에 무언가를 저장하는 법
변수 = 무언가;

// 변수 사용하는 법
변수 이름

 

var

  • 함수 스코프
  • 과거에 사용하던 변수 키워드
  • 중복 선언 가능
var x;
x = 10;

var y = 5;

 

let 

  • ES6에 새로 생긴 문법
  • 블록 스코프
  • 중복 선언 불가능, 재할당 가능
let x;
x = 10;

let y = 5;

 

 

const

  • 블록 스코프
  • 선언 후 값을 변경할 수 없음
const x = 10;
// x = 20; => 에러 발생

 

 


데이터 타입 (기본, 참조)

변수 타입 확인

// typeof 변수이름
// type을 알려주는 문자열을 반환한다.
let x = 10;
console.log(typeof x); // "number"

 

데이터 타입은 크게 기본 타입(하나가 들어있는 데이터)과 참조 타입(여러 개가 들어있는 데이터)로 나뉜다.

 

기본 타입

숫자(Number), 문자열(String), 불리언(Boolean), null, undefined, Symbol

// 숫자 (number)
let num = 10;
console.log(typeof num);  // "number"

// 문자열 (String)
let str = "hello";
console.log(typeof str);  // "String"

// 불리언 (boolean)
let bol = true;
console.log(typeof bol);  // "boolean"

// null
let nullValue = null;
console.log(typeof nullValue);  // "null"

// undefined
let undef = undefined;
console.log(typeof undef);  // "undefined"

// Symbol
let sym = Symbol('decription');
console.log(typeof sym);  // "Symbol"

참조 타입

객체(Object), 배열(Array), 함수(Function)

 

객체(Object)

// 객체 (Object)
// 추상화 = 공통점

// 객체를 만드는 법
변수이름 = {
	변수이름1: 값,
    변수이름2: 값
}

// 객체 안에 있는 변수를 사용하는 법
변수이름.변수이름1
변수이름["변수이름1"]


let student = {
	name = "psy",
	age = 10
}
console.log(typeof student);  // "Object"
console.log(student.name);  // "psy"
console.log(student.age);  // 10
console.log(student["name"]);  // "psy"

 

 

배열(Array)

// 배열 (Array)

// 배열 만드는 법
변수이름 = [값1, 값2, 값3];

// 배열 안에 있는 값 사용하는 법
변수이름[순서번호];

let arr = [1, 2, 3];
console.log(Array.isArray(arr));  // true (배열 확인)
console.log(arr[1]);  // 2

 

 

함수 (Function)

 

// 함수 만드는 법 1
function 함수이름() {
	함수를 실행했을 때 실행할 코드;
    return 함수를 실행한 곳에 들려줄 값;
}

// 함수 만드는 법 2 
const 함수이름 = (매개변수1, 매개변수2) => {
	함수를 실행했을 때 실행할 코드;
    return 함수를 실행한 곳에 들려줄 값;
}

// 함수 사용하는 법
함수이름(값1, 값2);

 

함수는 바뀔 일이 없어 보통 상수 변수에 저장한다. (const)

// 아래 네 개의 함수는 다 같은 함수
function add1(num1, num2) {
	return num1 + num2;
}

const add2 = function (num1, num2) {
	return num1 + num2;
}

const add3 = (num1, num2) => {
	return num1 + num2;
}

const add4 = (num1, num2) => num1 + num2;

 


호이스팅

변수 호이스팅이란?

  • 함수 안에 있는 모든 변수, 함수 선언들을 스코프의 최상단에 선언한 것처럼 동작하는 방식
  • const, let으로 선언한 변수는 선언, 초기화까지만 된 상태로 호이스팅되고 할당은 되지 않기 때문에 호이스팅이 안 된 것이 아니라 실행할 때 참조가 되지 않는 에러 발생

 

원래는 실행이 안 되는 게 맞는데, 호이스팅 때문에 선언 부분을 끌어올려놓고 실행한다.

func1("1번 함수");

function func1(message) {
	console.log(message);
}

func1("1번 함수");

// 출력 결과
// 1번 함수
// 1번 함수

 

 

화살표 함수는 const 로 저장하기 때문에 접근하지 못해서 에러 발생

func2("화살표 함수");

const func2 = (message) => console.log(message);
func2("화살표 함수");

// 츨력 결과
// Uncaught ReferenceError
// Cannot access 'func2' before initialization 에러

 

 

이런 호이스팅 특징 때문에 function으로 선언한 함수와 const 변수에 저장한 화살표 함수가 조금 다르다. (둘의 차이점 알아두기!)

 


스코프

스코프란?

: 변수에 접근할 수 있는 범위

 

 

함수 스코프

  • 함수 안에서만 유효한 범위를 가진다.
  • var

블록 스코프

  • 블록 안에서만 유효한 범위를 가진다.
  • const, let

글로벌 스코프

  • 전체 코드 안에서 유효한 범위를 가진다.
  • 함수 외부에서 선언된 변수는 어디서나 접근할 수 있다.

 

// 함수 스코프
const func = () => {
	if(true) {
    	var x = 10;
    }   
    console.log(x);
}

// 블록 스코프
const block = () => {
	if(true) {
    	let x = 20;
    }
    console.log(x);
}

func();  // 10
block();  // Uncaught ReferenceError
// 글로벌 스코프
let globalVar = 'global';
function glo() {
	let localVar = 'local';
	console.log(globalVar); // global
	console.log(localVar); // local
}

glo();
// console.log(localVar) => 에러 발생

연산자

산술 연산자 (+, -, *,  /, %)

let a = 10;
let b = 5;

console.log(a + b); // 15
console.log(a - b); // 5 
console.log(a * b); // 50
console.log(a / b); // 2 
console.log(a % b); // 0

 

 

비교 연산자 (==, ===, !=, !==, <, >)

let a = 10;
let b = 5;

// == : 같은지 비교
console.log(a == b); // false

// === : 값과 타입이 같은지 비교
console.log(a === b); // false

// != : 같지 않은지 비교
console.log(a != b); // true

// !== : 값과 타입이 다르면 true
console.log(a !== b); // true

// a < b : a가 b보다 작은지
console.log(a < b); // true

// a > b : a가 b보다 큰지
console.log(a > b); // false

 

 

논리 연산자 (&&, ||, !)

let a = true;
let b = false;

// AND && : 둘 다 true여야 true
console.log(a && b);  // false (AND: 둘 다 true여야 true)

// OR || : 하나라도 true면 true
console.log(p || q);  // true 

// NOT ! : true는 false로, false는 true로
console.log(!p);  // false

 

 

할당 연산자 (+=, -=, *=, /=, %=)

let x = 10;

// 단순 할당

x = 5;
console.log(x);  // 5


// 복합 할당

// x = x + 3
x += 3;
console.log(x);  // 13

// x = x - 3
x -= 3;
console.log(x);  // 7

// x = x * 2
x *= 2; 
console.log(x);  // 20

// x = x / 2
x /= 2; 
console.log(x);  // 5

// x = x % 5
x %= 7;
console.log(x);  // 3


연산자 우선 순위

괄호 > 산술 > 비교 > 논리

 


조건문과 반복문

조건문

if(조건1) {
	조건1이 참일 때 실행할 코드
} else if(조건2) {
	조건2가 참일 때 실행할 코드
} else {
	조건1도 거짓, 조건2도 거짓일 때 실행할 코드
}


let x = 10;
if (age >= 10) {
 console.log('10 이상입니다.');
} else {
 console.log('10 미만입니다.');
}

 

 

반복문

// for
for(초기값, 조건식, 증감식) {
	반복해서 실행할 코드;
}

for(let i = 0; i < 5; i = i + 1) {
	console.log(i);  // 0, 1, 2, 3, 4
}


// for each
for(변수이름 of 배열) {
	반복해서 실행할 코드;
}

let arr = [1, 2, 3, 4];
for(let n of arr) {
	console.log(n);  // 1, 2, 3, 4
}


//while
while (조건) {
	반복해서 실행할 코드;
	조건을 변경시키는 코드;
}

let count = 0;
while (count < 3) {
	console.log(count);  // 0, 1, 2
	count++;
}

 

728x90