본문 바로가기

개발/JavaScript

[Javascript] null VS undefined

 

그림으로 설명하는 0, null, undefined

 

 

  undefined null
공통점 '없음'을 나타냄
차이점 값이 대입되지 않은 변수나 속성을 사용하려고 할때 객체가 없을 때
typeof undefined object

 

undefined

변수 선언만 되어있고 값이 할당되어 있지 않은 상태

 

let a;
console.log(a) // 할당되지 않은 변수는 undefined

const obj = {};
console.log(obj.prop) // 할당되지 않은 객체의 값은 undefined

console.log(typeof undefined); // undefined의 type은 undefined

 

null

값이 있긴 한데 의도적으로 비어있는 값인 상태

const x = null;
console.log(x)

 

 

 

가급적 null을 사용하기

 

undefined는 코드 작성자가 의도적으로 빈 값을 유도했는지, logical error에 의해 빈 값이 나오는 건지 구분하지 못할 수 있기 때문이다.

 

 

reference

https://fierycoding.tistory.com/79

https://helloworldjavascript.net/pages/160-null-undefined.html