출처 : http://www.jakartaproject.com/board-read.do?boardId=javascripttip&boardNo=119681533125923&command=READ&t=1196858804183


질문) alert("" == 0) ;

        이렇게 하면 true , false 둘중 어느것이 나올까요?


  답은 true 입니다. 이상하지 않나요?



  if("" == 0 ) // with casting

  if("" === 0 )  // without casting

  즉 ""이 형변환이 되어 0으로 되서 true로 되었습니다.


  또  alert("" === 0) ;  이면  false가 됩니다.


 그리고 ""이 형변환해서 0이 된 이유는 아래와 같습니다.


 자바스크립트에서 null과 undefined의 차이점을 알아야 하는데요


In JavaScript, undefined means a variable has been declared but has not yet been assigned a value, such as:



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


null is an assignment value. It can be assigned to a variable as a representation of no value:



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


From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

Unassigned variables are initialized by JavaScript with a default value of undefined.

JavaScript never sets a value to null. That must be done programmatically.

As such, null can be a useful debugging tool. If a variable is null, it was set in the program, not by JavaScript.



null values are evaluated as follows when used in these contexts:

Boolean: false
Numeric: 0
String: “null”


undefined values are evaluated as follows when used in these contexts:

Boolean: false
Numeric: NaN
String: “undefined”


=============================================================================

----------------------------------------------------------------
 달팽이 
 
 이것도 궁금한데요.
undefined 를 확인할때
if(obj == undefined || obj == "undefined"){ ... }
이런식으로 체크를 해야하나요?
어떻게 보면
if(obj == null || obj == "null"){ ... }
이것과도 같은데 말이죠.
사이트 돌아다 보면 이런코드를 종종 보는데, 이것이 필요한건지..
----------------------------------------------------------------
 
 GoodBug   
undefined 체크는 다음과 같이 하세요
if (object === undefined)
혹은
if (typeof object == 'undefined')
 
null 비교는
if (object == null)을 해도 되지만 확실히 하기 위해서는
if (object === null)을 하는것이 좋습니다
=== 은 값 뿐만 아니라 type 까지 비교해주는겁니다
----------------------------------------------------------------

+ Recent posts