Coding

== vs === in JavaScript: Loose vs Strict Equality Explained

=== (strict equality) is true only when both values have the same type and the same value; == (loose equality) first converts the operands to a common type and then compares, so "1" == 1 is true but "1" === 1 is false. Use === everywhere, with one common, deliberate exception: x == null to test for both null and undefined.

What == does that === doesn't

When the two operands already have the same type, == and === give the same answer. They differ only when the types differ:

  • === returns false immediately. No conversion.
  • == converts one or both values and compares again. This is called type coercion.

The conversion rules for ==, from the ECMAScript IsLooselyEqual algorithm as documented by MDN, are applied in this order:

  1. Same type: compare directly. Objects are equal only if they are the same object.
  2. null or undefined: equal only to each other. null == undefined is true; null == 0 and null == false are false.
  3. Object vs primitive: convert the object to a primitive (arrays become strings like "1,2").
  4. Boolean vs anything: convert the boolean to a number, true to 1 and false to 0, then start again.
  5. Number vs string: convert the string to a number. A string that isn't numeric becomes NaN, which equals nothing.
  6. BigInt vs number or string: compare mathematical values.

Rule 4 is the source of most surprises. x == true does not ask "is x truthy?"; it asks "does x convert to the number 1?".

Surprising == results (tested)

Each line below was run in Node.js 18.18. You can paste any of them into a browser console and get the same result.

Expression== resultWhy
"1" == 1trueString converted to number 1
0 == ""trueEmpty string converts to 0
0 == "0"true"0" converts to 0
"" == "0"falseBoth strings, so no conversion: different characters
"\n" == 0trueWhitespace-only string converts to 0
false == "0"truefalse becomes 0, "0" becomes 0
false == "false"falsefalse becomes 0, "false" becomes NaN
2 == truefalsetrue becomes 1, and 2 is not 1
"true" == truefalsetrue becomes 1, "true" becomes NaN
[] == falsetrue[] becomes "", then 0; false becomes 0
[] == ![]true![] is false (arrays are truthy), then as above
[1,2] == "1,2"trueArray converted to the string "1,2"
null == undefinedtrueSpecial rule
null == 0falsenull equals only null and undefined
NaN == NaNfalseNaN is never equal to anything
0n == 0trueSame mathematical value

Two pairs in that table show why == is hard to reason about: 0 == "" and 0 == "0" are both true, yet "" == "0" is false. Loose equality is not transitive. Rewrite every line with === and all 16 are false.

A related trap: null == 0 is false, but null >= 0 is true. The relational operators (<, >= and friends) convert null to 0, while == has its own special case for null.

What === still gets "wrong": NaN and -0

Strict equality has two edge cases of its own, both from floating-point numbers:

NaN === NaN            // false
0 === -0               // true
Object.is(NaN, NaN)    // true
Object.is(0, -0)       // false

Object.is() is a third comparison that behaves like === except for those two cases. You rarely need it. To test for NaN, use Number.isNaN(x). Because indexOf and switch use strict equality, [NaN].indexOf(NaN) returns -1 and case NaN: never matches; [NaN].includes(NaN) returns true because includes uses a variant that treats NaN as equal to itself.

Objects: neither operator compares contents

const a = { key: "value" };
const b = { key: "value" };
a == b    // false
a === b   // false
a === a   // true

Both operators compare object references. Two objects, arrays or new String("hello") wrappers created separately are never equal, however identical they look. Compare fields explicitly, or use a deep-equality function from your test framework or Node's util.isDeepStrictEqual.

When == is acceptable: checking for null or undefined

Because null and undefined are loosely equal only to each other, this one line covers both and nothing else:

if (value == null) {
  // value is null or undefined; 0, "" and false do NOT get here
}

The strict spelling is value === null || value === undefined. Both are correct; choose one and be consistent. Many codebases allow exactly this exception. For the common case of supplying a default, the ?? operator is clearer still: const port = options.port ?? 3000 uses 3000 only when options.port is null or undefined.

Do not use == as a shortcut for truthiness. if (x == true) fails for 2, "yes" and every object. If you mean "truthy", write if (x); if you mean exactly true, write if (x === true).

Enforce === with ESLint

The eqeqeq rule flags every == and !=. To keep the == null exception, configure it like this:

"eqeqeq": ["error", "always", { "null": "ignore" }]

The "smart" option goes further and also allows == between two literals and in typeof x == "string" checks, where both sides are always strings so the result cannot differ. ESLint only autofixes those safe cases; for anything else, switching an operator changes behaviour if the types really do differ, so review each one. Typically the bug was the ==.

Converting a comparison safely

If == was relying on a conversion, make it explicit instead of losing it. Form input is the common case, since input values are always strings:

// before: relies on "5" == 5
if (input.value == 5) { ... }

// after: the conversion is visible
if (Number(input.value) === 5) { ... }

Number("") is 0 and Number(" 5 ") is 5, the same as the hidden conversion was, so check whether an empty field should really count as zero. The same old-versus-new split exists for variable declarations: see var vs let vs const.

Frequently asked questions

Is === faster than == in JavaScript?
Not in a way you should design around. When both operands already have the same type, == and === do the same comparison. Pick === because its result is predictable, not for speed.
What is the difference between != and !==?
They are the negations of == and ===. a != b is the same as !(a == b) and converts types first; a !== b is the same as !(a === b) and never converts. So '1' != 1 is false, while '1' !== 1 is true.
How do I compare two objects or arrays by their contents?
Neither == nor === can do it: both compare object references, so two separate objects with identical contents are never equal. Compare the fields you care about, or use a deep-equality helper such as Node's util.isDeepStrictEqual or the assertion library in your test framework.
How do I check for NaN?
Use Number.isNaN(x). Both NaN == NaN and NaN === NaN are false. The older global isNaN() converts its argument first, so isNaN('abc') is true even though 'abc' is a string, not NaN; Number.isNaN('abc') is false.

Sources