본문 바로가기
공부 기록

null VS undefined

by 매트(Mat) 2022. 6. 13.

null VS undefined

비슷하면서도 비슷하지 않은(?) nullundefined의 차이점에 대해 알아보자.

null

null은 변수 선언과 동시에 값(value)을 할당할 수가 있다. 즉, null은 값인데 존재하지 않는, 비어있는, 알 수 없는 값이다.
예를 들어, hello라는 변수에 아직 인사말을 못정해서 어떤 값을 할당해야 할지 모르겠다면 null을 넣어주면 된다. null의 타입은 object다. 타입은 object이지만 string, number, bigint, boolean, symbol, null, undefined는 모두 원시형 값이다.

let hello = null; //변수 선언
console.log(hello); //null
console.log(typeof hello); //object

hello = '안녕하세요~';
console.log(hello); //안녕하세요~

undefined

undefined는 변수 선언은 했지만, 값(value)을 할당하지 않았을 때 undefined가 된다. 타입도 undefined가 된다.

let hello; //변수 선언
console.log(hello); //undefined
console.log(typeof hello); //undefined

null과 undefined의 차이점 정리

null은 변수 선언과 값을 할당하는 것을 말하고, undefined는 변수 선언과 값을 할당하지 않는 것을 말한다.
nullundefined를 비교했을 때 값과 타입까지 비교하는 ===에서는 false를 반환하지만 타입을 제외하고 단순히 값만 비교했을 때 ==에서는 true를 반환한다.

console.log(null === undefined); //false
console.log(null == undefined); //true

참고 자료

댓글