Strong Root

Loose Comparison (==)

1
2
3
var x = 10;
var y = "10";
if (x == y)    // returns true
cs




Strict Comparison (===)

1
2
3
var x = 10;
var y = "10";
if (x === y)    // returns false
cs






swtich 문에는 Strict Comparison 이 적용된다.

1
2
3
4
var x = 10;
switch(x) {
    case 10alert("Hello");    // display an alert
}
cs




1
2
3
4
var x = "10";
switch(x) {
    case 10alert("Hello");    // not display an alert
}
cs






출처 : http://www.w3schools.com/js/js_mistakes.asp

만약 함수가 호출될 때 인자를 다 넣어주지 않는다면, 넣어주지 않은 인자값들은 undefined가 된다.


그리고 이 undefined 값들은 함수 코드의 안정성을 해칠 수 있다.


따라서 인자값들에 대해서 default 값을 세팅해주는 습관을 들이는 것이 좋다.




1
2
3
4
5
function myFunction(x, y) {
    if (y === undefined) {
        y = 0;
    }
}
cs






출처 : http://www.w3schools.com/js/js_best_practices.asp

== 는 비교 전에 항상 matching type 으로 형변환을 시킨다.


=== 는 값 뿐만아니라 타입까지 강제적으로 비교한다.




1
2
3
4
5
6
7
0 == "";        // true
1 == "1";       // true
1 == true;      // true
 
0 === "";       // false
1 === "1";      // false
1 === true;     // false
cs






출처 : http://www.w3schools.com/js/js_best_practices.asp

typeof 는 Array, Date, Object 모두 "object" 를 리턴하여 구분이 불가능하므로, constructor 를 이용하여 해결한다.




1
2
3
function isArray(myArray) {
    return myArray.constructor.toString().indexOf("Array"> -1;
}
cs




1
2
3
function isDate(myDate) {
    return myDate.constructor.toString().indexOf("Date"> -1;
}
cs






출처 : http://www.w3schools.com/js/js_type_conversion.asp