반응형

undefined는 원시값으로, 선언한 후 값을 할당하지 않은 변수 혹은 값이 주어지지 않은 인수에 자동으로 할당됩니다.

var a;

if(typeof a === 'undefined') {
        console.log('a is typeof undefined');
}

if (a === undefined) {
        console.log('a is undefined');
}

 

그렇다면 선언하지 않은 변수는 어떻게 되나???

if (b === undefined) {
        console.log('b is undefined');
}

===> ReferenceError 발생.

 

if (typeof b === 'undefined') {
        console.log('b is typeof undefined');
}

===> 오류 없이 로그 출력.

 

 

결론... typeof 를 사용하자??!!!

typeof를 사용하는 이유 중 하나는 선언하지 않은 변수를 사용해도 오류를 던지지 않기 때문이다.

 

반응형

'프로그래밍 > Javascript' 카테고리의 다른 글

prototype  (0) 2018.12.20
javascript containsAll  (1) 2016.11.04
[jquery] hide, show 함수, visibility 속성  (0) 2016.10.28
jquery crossdomain ajax jsonp  (1) 2015.10.30
한글, 영문 check  (0) 2011.12.27

+ Recent posts