WebMasterCampus
WEB DEVELOPER Resources

Javascript Double Equals vs Triple Equals Comparison Operator

Learn how Javascript double equals vs triple equals comparison operator works


Javascript Double Equals vs Triple Equals Comparison Operator

The identity (===) operator behaves identically to the equality (==) operator except no type conversion is done, and the types must be the same to be considered equal.

The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. Both are equally quick.

If the two operands are of the same type and have the same value, then === produces true and !== produces false. The double == and != do the same thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values.

Example 1


1919 === '1919'

0 == false
0 === false

"" == false
"" === false

Following are some of the interesting cases:

Example 2


var a = [1,2,3];
var b = [1,2,3];

var c = { x: 1, y: 2 };
var d = { x: 1, y: 2 };

var e = "text";
var f = "te" + "xt";

a == b            // false
a === b           // false

c == d            // false
c === d           // false

e == f            // true
e === f           // true

The special case is when you compare a literal with an object that evaluates to the same literal, due to its toString or valueOf method. For example, consider the comparison of a string literal with a string object created by the String constructor.

"abc" == new String("abc")    // true
"abc" === new String("abc")   // false

Here the == operator is checking the values of the two objects and returning true, but the === is seeing that they’re not the same type and returning false. Which one is correct? That really depends on what you’re trying to compare.

Reference: http://www.ecma-international.org

Created with love and passion.