What is the difference between == and ===?

=== (strict equality) compares value and type with no conversion; == (loose equality) converts the operands to a common type first, which leads to surprising results.

How == converts

The rules are long, but the common cases are:

  • null == undefined is true, and neither equals anything else.
  • If one side is a number and the other a string, the string is converted to a number.
  • Booleans are converted to numbers first (true → 1, false → 0).
  • Objects are converted to primitives (via valueOf / toString) before comparing.

That is why "" == 0, "0" == false and [] == false are all true, yet "" == "0" is false. Loose equality is not even transitive.

What === still does not handle

  • NaN === NaN is false. Use Number.isNaN(x).
  • +0 === -0 is true. Use Object.is(a, b) if the difference matters.
  • Objects are compared by reference, so two equal-looking objects are not ===.

Object.is is "same value" equality: like === but Object.is(NaN, NaN) is true and Object.is(0, -0) is false.

Best practice

Always use ===. The one widely accepted exception is value == null, which checks for both null and undefined in one go.

Code example

js
1console.log(5 == "5"); // true (string converted to number)
2console.log(5 === "5"); // false (different types)
3
4console.log("" == 0); // true
5console.log("0" == false); // true
6console.log("" == "0"); // false <- loose equality is not transitive
7console.log([] == false); // true
8
9console.log(null == undefined); // true
10console.log(null === undefined); // false
11console.log(null == 0); // false
12
13console.log(NaN === NaN); // false
14console.log(Number.isNaN(NaN)); // true
15console.log(Object.is(NaN, NaN)); // true
16console.log(Object.is(0, -0)); // false
17
18// The accepted shortcut: check for null OR undefined
19function hasValue(x) {
20 return x != null;
21}
22console.log(hasValue(0), hasValue(""), hasValue(null), hasValue(undefined)); // true true false false

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app