References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript Loose Equality == operator

Operator JavaScript All modern browsers Updated
Quick answer

The loose equality operator == compares two values after coercing them to a common type. That causes surprises: 0 == "", 0 == false and null == undefined are all true. Prefer strict equality (===), which doesn't coerce. The one common exception is x == null to match null or undefined together.

Overview

== checks whether two values are equal, but first it coerces them to a common type — and that type juggling is the source of a famous gallery of confusing results. 1 == "1" is true (the string becomes a number), 0 == false is true, 0 == "" is true, and null == undefined is true. These rules are hard to remember and easy to trip over.

Because of that, the widely accepted advice is to avoid == and use === (strict equality), which requires the same type and never coerces. Almost every style guide and linter flags == for this reason. Using === everywhere means you never have to recall the coercion table.

There is one deliberate, idiomatic exception: x == null. Thanks to the coercion rules, it's true for both null and undefined and nothing else — a handy shorthand for "is this value missing?" Beyond that single pattern, reach for ===. Note also that, like all comparisons, anything compared to NaN is false (even NaN == NaN).

Syntax

a == b

1 == "1"            // true  (string coerced to number)
0 == false          // true
0 == ""             // true
null == undefined   // true
NaN == NaN          // false

x == null           // the one idiomatic use (null OR undefined)

Example

Live example
<pre id="out" style="font:14px ui-monospace,monospace"></pre>
<script>
  const tests = [
    ['1 == "1"',        1 == '1'],
    ['0 == false',       0 == false],
    ['0 == ""',         0 == ''],
    ['null == undefined', null == undefined],
    ['1 === "1"',       1 === '1']
  ];
  document.getElementById('out').textContent =
    tests.map(t => t[0].padEnd(18) + ' -> ' + t[1]).join('\n');
</script>

Best practices

  • Use === by default — avoid == and its coercion surprises.
  • The one common exception is x == null to test for null or undefined together.
  • Never compare with NaN using ==; use Number.isNaN().
  • Most linters flag == for a reason — let them.

Frequently asked questions

What is the difference between == and === ?
== coerces the operands to a common type before comparing; === requires the same type and value with no coercion. Use ===.
Why is 0 == "" true?
Loose equality coerces both to numbers: the empty string becomes 0, so 0 == 0 is true. With === it's false.
When is it OK to use ==?
The common accepted use is x == null, which matches both null and undefined. Otherwise prefer ===.
Is null == undefined true?
Yes. With loose equality they're equal to each other (and to nothing else). With === they're not.