let
const
는 선언 단계와 초기화 단계가 별개로 이루어진다.
호이스팅이 이루어지며 선언은 실행되지만, 초기화는 런타임에 이루어지기 때문에, var
과는 달리 먼저 참조가 불가능하다.
console.log(a) // ReferenceError: a is not defined (오류 발생)
console.log(b) // ReferenceError: b is not defined (오류 발생)
let a
const b = undefined
console.log(a) // output : undefined
console.log(b) // output : undefined
블록(if문, for문, 함수 등)에서 할당 된 변수는 해당 블록의 지역 변수로 인정된다.
let ex = 1;
console.log(ex) // output : 1
if(true){
let ex = 20;
let ex2 = 'a';
console.log(ex)
}
console.log(ex) // output : 20
console.log(ex2) // ReferenceError: ex2 is not defined (오류 발생)
let
은 재할당은 가능하지만, 재선언은 불가능하다.
let ex = 0;
ex = 'abc'
console.log(ex) // output : 'abc'
let ex = 0 // SyntaxError: Identifier 'ex' has already been declared. (오류 발생)
const
는 재할당도, 재선언도 전부 불가능하다. 단, 객체/배열 내의 값은 변경이 가능하다. (주소를 할당하기 때문!)
if(true){
const ex = 1;
ex = 1 // TypeError: Assignment to constant variable. (오류 발생)
console.log(ex) // output : 1
}
if(true){
const ex = [2, 2, 3]
ex = [2,3,4] // TypeError: Assignment to constant variable. (오류 발생)
ex[0] = 1
console.log(ex) // output : [1, 2, 3]
}
또한, const
는 선언과 초기화를 동시에 해야하는 특징이 있다.
const a // SyntaxError: Missing initializer in const declaration.
const b = 1;
다음과 같이 선언과 초기화를 동시에 해주지 않으면 오류를 뿜어내게 된다.
ES6에서 var
의 문제점들을 해결하기 위해 나온것이 let
, const
키워드인만큼, var
보다는 let
이나 const
를 사용하는 것이 더 좋은 습관이 될 수 있다.