Using the == versus the strict === operator
- alert("1" == 1); // => true
- alert(false == "0"); // => true
Here are a few more cases:
- alert(null == undefined); // => true
- alert(true == "1"); // => true
- alert("9" < "P"); // => true
In the last expression, the ASCII values for numbers are lower than those for letters, returning true.
- alert("1" === 1); // => false
- alert(true === !false); // => true
- var ref1 = [10, 20]; // an array
- var ref2 = [10, 20]; // a second array
- alert(ref1 == ref2); // => false
- alert(ref1 === ref2); // => false
Here ref1 == ref2 returns false, because they reference different arrays. The strict comparison ref1 === ref2 also return false because, although they have the same values, these are two different arrays in memory.
- var str1 = "Hello World"; // a string
- var str2 = "Hello" + " World"; // another string
- alert(str1 == str2); // => true
- alert(str1 === str2) // => true
Here str1 and str2 reference the same immutable "Hello World" string and therefore both == and === return true.
How about comparing string objects created with the String constructor and with a string literal?
- alert("Hello" == new String("Hello")); // => true
- alert("Hello" === new String("Hello")); // => false
The == operator converts these objects on either side to the same type and then returns true because their values are the same. The === operator understands that the objects are not of the same type and therefore immediately returns false without even looking at their values.