본문 바로가기

[JAVASCRIPT] undefined, null

by 식 2014. 10. 8.

자바스크립트에서 가장 많은 혼돈을 주는 것중의 하나가 바로 null과 undefiend이다. 다른 언어의 경우는 보통 null로 통일되어 있기 때문에 이 두 가지 타입에 대해 구분하는 것이 쉽지 않다.

  그렇다면, 먼저 undefined에 대해서 알아보자.

  변수가 선언된 적이 없거나, 선언이 되었더라도 아직 값이 할당되지 않았다면 undefined 인 상태이다. 즉, 특별한 값이 할당되기 전에 자동으로 설정하는 값이 undefined라고 생각하면 된다.

  1. // a 를 선언하지 않음  
  2. //console.log( a );  -- Exception 발생!!  
  3. console.log( typeof a );  // "undefined", typeof 연산자는 아래 참조  
  4.   
  5. // b 를 선언하였으나 값을 할당하지 않음  
  6. var b;  
  7. console.log( b );   // undefined  
  8. console.log( typeof b ); // "undefined"  
  9.   
  10. console.log( window.xxx );  // Exception 발생하지 않음, undefined  

  일단, 변수가 선언된 적이 없으면 Exception이 발생되고 스크립트 실행이 멈춘다. 특이하게도 객체(object)에 없는 속성을 참조할 때는 Exception이 발생하진 않는다. (물론, window.xxx() 처럼 객체에 존재하지 않는 메소드를 직접 호출하는 경우에는 Exception이 발생한다.)

     typeof  typeof는 연산자에 해당한다. 즉, +, -와 같은 연산자로 typeof val 로 해당 val의 타입을 문자열로 리턴하게 된다. 

      이 연산자는 메소드나 함수를 호출할 때, 특정 인자값이 존재하는지 검사하기 위해서 작성하는 다음과 같은 if문으로 인해 Exception이 발생하여 코드실행 자체가 멈추는 것을 방지하는 효과가 있다. (물론 null인지 여부는 다시 검사를 해야 한다.)

    if ( val != undefined ) { .. } 대신, if ( typeof val != "undefined" ) { ... }

      typeof연산자의 리턴 문자열은 다음과 같다.
    Type of valUndefinedNullBooleanNumberStringObjectFunction
    Result"undefined""object""boolean""number""string""object""function"



  그에 반해서 null은 명시적으로 개발자가 빈 값(empty)임을 지정하기 위해서 사용된다.

  1. var a = 10;    
  2. console.log( typeof a );    // number   
  3.     
  4. a = null;    
  5. console.log( typeof a );    // object    
  6.     
  7. a = undefined;    
  8. console.log( typeof a );    // undefined    

  그러나, 단순비교(==) 연산자는 null과 undefined를 동일하게 취급한다는 점을 기억하는 것이 좋겠다. 다음의 예에서 대부분의 결과값은 true이다.

  1. var a = null;  
  2.   
  3. console.log( a == null );  
  4. console.log( a == undefined );  
  5. console.log( a === null );  
  6. console.log( a === undefined ); // false  
  7.   
  8. var b = undefined;  
  9.   
  10. console.log( b == null );  
  11. console.log( b == undefined );  
  12. console.log( b === null );      // false  
  13. console.log( b === undefined );  
  14.   
  15.   
  16. console.log( typeof a );    // object  
  17. console.log( typeof b );    // undefined  
  18.   
  19. 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
TIP : Objective C Naming style.  (0) 2012.09.05
ERROR : Apple's web service operation was not successful  (0) 2012.09.04