In this post I would like to explain the difference between double (
==) and triple (
== does type coercion (conversion) before checking for equality; and
=== does strict equation which requires values to have the same type as well.
Here is what it means:
0 == false // true 0 === false // false, because they have different types (int, bool) 1 == "1" // true 1 === "1" // false, because they have different types (int, string) null == undefined // true null === undefined // false
Detailed (longer) explanation
- When comparing a number and a string, the string is converted to a number value.
- When comparing a boolean, the boolean is converted to 1 if it is
trueand +0 if it is
- When object is compared with a number or a string, the object is converted to its’ default value (
.toString()). If these methods are missing a runtime error is thrown.
- When comparing an object and another object, no type conversion is made. They are equal only if they refer the same object.
"foo" === "foo" // true, both operands are of type String new String("foo") === new String("foo") // false, 2 Objects refer diff object instances
Detailed comparison information can be found on Mozilla Developer Network page. Here is the summary:
- Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions
- Two numbers are strictly equal when they are numerically equal (have the same number value). NaN is not equal to anything, including NaN. Positive and negative zeros are equal to one another
- Two Boolean operands are strictly equal if both are
trueor both are
- Two distinct objects are never equal for either strictly or abstract comparisons
- An expression comparing Objects is only true if the operands reference the same Object
- Null and Undefined Types are