const, let
- const와 let은 block scope이다.
- 다른 언어들이 사용하는 형태이다.
if(true){
const a = 0;
}
/*
* if 블록에서 할당한 a변수는 참조할 수 없다.
*/
console.log(a); // ReferenceError: a is not defined
두개의 변수 정의
let a = 'hello';
console.log(a); // hello
/*
* 바깥의 a 변수와 if블록 내의 a변수 둘다 사용하지만, 가까운 a 변수를 참조하게 된다.
*/
if(true){
let a = 'world';
console.log(a); // world
}
/*
* if 블록 안의 변수는 참조할 수 없기 때문에 바깥에 있는 변수인 'hello'를 참조하게 된다.
*/
console.log(a); // hello
hoisting
/*
* var에서 사용했던 호이스팅 방식으로 진행하면 const와 let은 ReferenceError를 발생시킨다.
*/
console.log(a); // ReferenceError: a is not defined
const a = 'hello';
const와 var과의 차이점
/*
* const로 정의되어진 변수는 재할당이 불가능하다.
*/
const a = 'hello';
a = 'world'; // TypeError: Assignment to constant variable.
var b = 'hello';
b = 'world'; // 재할당이 가능하다.
let c = 'hello';
c = 'world'; // 재할당이 가능하다.
/*
* const로 정의되어진 내부 객체의 속성값은 수정이 가능하다
*/
const obj = { prop1: 'a'};
obj.prop1 = 'b';
obj.prop2 = 123;
console.log(obj); // { prop1: 'a', prop2: 123 }
const arr = [10,20];
arr[0] = 100;
arr.push(300);
console.log(arr); // [100, 20, 300]