자바스크립트에서 가장 많은 혼돈을 주는 것중의 하나가 바로 null과 undefiend이다. 다른 언어의 경우는 보통 null로 통일되어 있기 때문에 이 두 가지 타입에 대해 구분하는 것이 쉽지 않다.
그렇다면, 먼저 undefined에 대해서 알아보자.
변수가 선언된 적이 없거나, 선언이 되었더라도 아직 값이 할당되지 않았다면 undefined 인 상태이다. 즉, 특별한 값이 할당되기 전에 자동으로 설정하는 값이 undefined라고 생각하면 된다.
- // a 를 선언하지 않음
- //console.log( a ); -- Exception 발생!!
- console.log( typeof a ); // "undefined", typeof 연산자는 아래 참조
- // b 를 선언하였으나 값을 할당하지 않음
- var b;
- console.log( b ); // undefined
- console.log( typeof b ); // "undefined"
- console.log( window.xxx ); // Exception 발생하지 않음, undefined
일단, 변수가 선언된 적이 없으면 Exception이 발생되고 스크립트 실행이 멈춘다. 특이하게도 객체(object)에 없는 속성을 참조할 때는 Exception이 발생하진 않는다. (물론, window.xxx() 처럼 객체에 존재하지 않는 메소드를 직접 호출하는 경우에는 Exception이 발생한다.)
그에 반해서 null은 명시적으로 개발자가 빈 값(empty)임을 지정하기 위해서 사용된다.
- var a = 10;
- console.log( typeof a ); // number
- a = null;
- console.log( typeof a ); // object
- a = undefined;
- console.log( typeof a ); // undefined
그러나, 단순비교(==) 연산자는 null과 undefined를 동일하게 취급한다는 점을 기억하는 것이 좋겠다. 다음의 예에서 대부분의 결과값은 true이다.
- var a = null;
- console.log( a == null );
- console.log( a == undefined );
- console.log( a === null );
- console.log( a === undefined ); // false
- var b = undefined;
- console.log( b == null );
- console.log( b == undefined );
- console.log( b === null ); // false
- console.log( b === undefined );
- console.log( typeof a ); // object
- console.log( typeof b ); // undefined
- console.log( typeof x ); // 미선언변수, undefined
null과 undefined를 완벽히 구분하고자 한다면 동치비교(Strict Equal, ===)을 사용하는 것이 좋다. 우리가 기억해야 할 것은 의도를 담았느냐 그렇지 않으냐로 구분해야 된다는 점과, undefined 변수나 함수를 호출하면 Exception이 발생하므로 주의해야 한다는 점이다.
따라서, 변수를 사용하기 전에 항상 var로 명시적으로 선언하여 사용하는 것이 좋은 코딩 습관이라 하겠다. - See more at:
출처 : http://www.deadfire.net/jscript/projscript006.html#sthash.iHP2K1e7.dpuf
'일' 카테고리의 다른 글
Swift 공부방법 (0) | 2016.02.02 |
---|---|
비동기IO와 Non blocking IO차이 (0) | 2015.12.09 |
MYSQL 테이블 복사 (0) | 2014.09.13 |
테이블복사 (0) | 2011.11.23 |
Struct Size (0) | 2009.10.12 |