Comparing Values

Comparing Primitives without Casting aka Strict Comparison

The operators === and !== are used to compare two operands without casting their data types. In other words, when operands are of different data types === always returns false and !== always returns true. When operands have the same primitive data types and the same values === returns true and !== returns false.

42 === '42' // => false
42 !== '42' // => true
42 === 42 // true
42 !== 42 // false
0 === -0 // => true
null === undefined // => false

Strict comparison operator is used by Array.prototype.indexOf.

Comparing Primitives with Casting aka Abstract Comparison

When two operands are compared using == and != JavaScript will first try to type cast them to match if necessary and only then compare their values.

42 == 42 // => true
42 == '42' // => true
42 != '42' // => false
1 == true // => true
2 == true // => false
0 == false // => true
0 == undefined // => false
NaN == NaN // => false
0 == null // => false
0 == -0 // => true
null == undefined // => true

Comparing Objects

Both strict and abstract comparisons are primarily used to compare primitives. Comparing two different objects - even with the exact same structure - returns false irrespective whether the comparison is effected with === or ==.

{} === {} // => false
{} == {} // => false

a = { a: 1 }
b = { a: 1 }
a == b // => false

Other Comparison Algorithms

In addition to === and == there are two other comparison algorithms in ES2015: SameValueZero and SameValue.