JS 자료형을 공부하던 도중 궁금한 점을 조금 심도있게 톺아본다.
둘 다 모두 변수에 할당할 수 있으며 비어있는 상태를 말한다.
공통점
차이점
// 동등 연산자 == (자료형 변환이 일어난다.)
console.log(null == undefined); // true
// 일치 연산자 ===
console.log(null === undefined); // false
// 하위호환을 위해 'null' 이 아니다.
console.log(typeof null); // 'object'
console.log(typeof undefined); // undefined
// undefined 는 전역객체
console.log(window.undefined); // undefined
// undefined 는 예약어가 아니기 때문에 변수명으로 사용가능하다.
let undefined;
console.log(undefined);
모두 변수를 선언하는 예약어이다. ES(ECMASCript)5 까지는 변수 선언할 때 var 만 썻어야했다. ES6 부터는 const 와 let 을 쓸 수 있게 되었다. 왜 const 와 let 이 도입되었을까? var 에는 우선 2가지 문제가 있다.
// 재선언
var a;
var a; // 오류가 나지 않는다.
// 함수범위
const a = "foo";
if (a === "foo") {
var result = true;
}
console.log(result); // true
2가지의 문제는 프로그래머의 실수를 보호해주지 않는다. const 와 let 은 2가지의 문제를 해결한다. const 와 let 으로 선언한 변수는 재선언이 불가능 하고 block scope(블록범위) 로 사용 가능하다. const 와 let 의 차이는 불변성이다. const 로 선언한 변수는 수정이 불가하다.
const a = "foo";
let a; // Identifier 'a' has already been declared
if (a === "foo") {
const result = true;
}
console.log(result); // result is not defined
const 로 선언한 변수는 변경이 불가능하다. 하지만 object 나 array 인 경우는 다르게 작동한다.
const a = "foo";
a = "bar"; // Assignment to constant variable.
const b = {};
b.key = "value"; // 정상 작동
const c = [];
c.push("foo"); // 정상 작동
직관적으로 생각하면 불변해야하는 변수가 바뀌고 있다. 이상하지 않은가? object 와 array 는 주소값을 참조하고 있기 때문에 주소값을 바꾸지 않는 이상 오류를 뱉지 않는다. object 의 경우 Object.freeze() 를 통해 수정이 불가능하게 할 수 있다.
const a = {};
a.key = "value";
console.log(a); // {key: 'value'}
Object.freeze(a);
a.key = "something" // 오류가 나지는 않는다.
console.log(a); // {key: 'value'}
인용