JavaScript Equality Operators

By

Published · Updated

Tagged: JavaScript

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

Those operators accept two values and return a boolean:

Let’s talk what we mean for strict. == does not convert the second operand to the type of the first. It follows fixed rules, regardless of order: null and undefined only equal each other; if one side is a number and the other a string, the string becomes a number; booleans become numbers; objects get converted to primitives; BigInt compares by mathematical value with numbers and strings. === skips that and compares type and value as they are. I also have a short == vs === post.

Examples:

const a = true

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

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

You cannot check objects for equality: two objects are never equal to each other. The only case when a check might be true is if two variables reference the same object.

Some peculiarities to be aware: NaN is always different from NaN. Use Number.isNaN() to check for it.

Object.is() (ES2015) is like ===, except Object.is(NaN, NaN) is true and Object.is(0, -0) is false. I wrote about Object.is().

NaN == NaN //false

null and undefined values are equal if compared in non-strict mode:

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

Test comparisons live

Try any two values below to compare ==, ===, and Object.is() and see the type coercion steps behind ==:

JS equality explorerInteractive · runs in your browser

Classic gotchas

Value A

Value B

Results

OperatorResult
A == B
A === B
Object.is(A, B)

Truthiness

ValueTruthy?
A
B

== coercion steps

Want me to talk about your product? You can sponsor this site.

Related posts about js: