Values and variables

JavaScript Equality Operators

Learn the JavaScript equality operators ==, !=, === and !==, the difference between strict and loose checks, and quirks like NaN never equaling NaN.

Equality operators compare two values and return true or false:

  • == loose equality
  • != loose inequality
  • === strict equality
  • !== strict inequality

Strict means no type conversion. Loose converts one operand to match the other before comparing.

Examples:

const a = true

a == true //true
a === true //true

1 == 1 //true
1 == '1' //true
1 === 1 //true
1 === '1' //false

My default is ===. It compares value and type, so fewer surprises show up in real code.

Two objects are never equal unless they are the same reference:

{} === {} //false
const left = { id: 1 }
const right = left
left === right //true

NaN is never equal to itself, even with loose equality:

NaN == NaN //false
NaN === NaN //false

Use Number.isNaN(value) when you need to detect NaN.

null and undefined are equal under loose equality only:

null == undefined //true
null === undefined //false

That pair is why value == null checks for both missing sentinels in one test.

Run these in order: 0 == false, 0 === false, '' == 0, '' === 0. Loose equality treats them as equal. Strict equality does not.

Arrays and objects follow the reference rule even with loose equality:

[1] == [1] // false
[1] === [1] // false

Only the same reference compares true. That is why comparing fetched JSON objects with === usually means “is this the exact same object in memory”, not “do these contain the same data”.

For deep structural equality you need a helper or a loop. For everyday checks, compare the fields you care about.

The Object.is() static method handles two edge cases === misses: Object.is(NaN, NaN) is true, and Object.is(+0, -0) is false.

When a function accepts optional config, I often accept undefined and apply defaults inside the body rather than relying on loose equality at the call site.

I built a free JS equality explorer where you can try any comparison and see the coercion steps behind it.

Lesson completed