Comparing Values in JavaScript

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.

We use cookies and similar technologies to enhance the quality of services, maintain statistics and adjust marketing content. You will find more information in the Cookies Policy.

By clicking OK you grant consent to processing of your personal data by us and our Trusted Partners with the purpose of maintain statistics and adjustment of the marketing content pursuant to the Privacy Policy. If you wish to not grant that consent and/or limit its extent click Settings.