In this post I would like to explain the difference between double (==
) and triple (===
) equals in JavaScript/jQuery. A quick and short explanation is that ==
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 you use == the javascript interpreter will convert one side of the comparison according to these rules:
- 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
true
and +0 if it isfalse
. - When object is compared with a number or a string, the object is converted to its’ default value (
.valueOf()
,.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.
When you use === the javascript interpreter will not convert values to primitive types and make sure that the operands have the same value as well as the same type.
"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
true
or both arefalse
- 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
==
(but not===
)