##undefined와 null 의 차이는 무엇일까?

일단 console창에 쳐본다.

undefined

var demo;
alert(demo); //shows undefined 
alert(typeof demo); //shows undefined

null

var demo = null;
alert(demo); //shows null
alert(typeof demo); //shows object

undefined는 변수를 선언만 하고 타입이 결정되있지 않지만 null은 object라는 타입이 찍힌다. 사실 큰 차이가 없어보인다. 그러면 보통 어떨때 사용할까?

아래 예시를 보자

var useUnde = { isInit : undefined};
console.log(useUnde.isInit);
//undefined

var notuseAny = {};
console.log(notuseAny.isInit);
//undefined

var useNull = { isInit : null};
console.log(useNull.isInit);
//null

오브젝트 의 isInit 값을 초기화 할때 useUnde 처럼 파라미터를 undefined로 하나 notuseAny 처럼 아무 값도 적어주지 않으나 결과가 똑같다.

만약 isInit 값이 오브젝트 내 파라미터가 아니라 전역변수라면 undefined로 라도 초기화 해주지 않으면 에러가 뜬다

즉 오브젝트 내 파라미터 값을 비어둔채 명시적으로 초기화 할때는 null을 사용해야 초기화되었음을 알수 있다.

undefined와 null의 메모리적 측면

결론은 두 값 다 메모리적으로도 큰 차이가 없다 .. 굳이 따지자면 undefined가 알파벳이 더 많아서 코드상 메모리를 더 잡아먹는다. garbage collection에서도 아무 상관없다. null, undefined, {} or 42도 마찬가지이다. garbage collection이 수행되기 위해서는 heap에 있는 오브젝트와 변수의 연결이 없을때이다. 즉 오브젝트나 해당 변수가 unreachable 해지면 grabage collection의 후보가 된다.

메모리적 측면 참고 : Javascript memory impact of null vs undefined

가비지 콜렉션 참고 : Are null and undefined equally valid for explicitly making objects unreachable?