JavaScript Operators, Type Coercion, and == vs ===

JavaScript converts values between types automatically, and that behavior decides whether "5" == 5 is true and why [] + {} produces a string. The loose equality operator (==) applies type coercion before comparing. The strict equality operator (===) never does. Learn the exact conversion rules and you can predict every result without memorizing trivia.

Quick Takeaways

  • === compares type and value with no conversion. Use it by default.
  • == runs the Abstract Equality Comparison algorithm, which coerces operands to a common type, mostly Number.
  • + concatenates if either operand becomes a string. Every other arithmetic operator converts to Number.
  • NaN, null, and undefined are the three values where equality behaves unlike anything else. Handle them explicitly.
Feature == (Loose) === (Strict) Object.is()
Type coercion Yes No No
NaN equals NaN false false true
+0 equals -0 true true false
null equals undefined true false false
Predictability Low High High
Recommended default No Yes Special cases

JavaScript Operators: The Categories That Trigger Coercion

JavaScript has seven operator groups. Four of them interact heavily with type coercion.

Category Examples Coerces operands?
Arithmetic + - * / % ** Yes (to Number, or String for +)
Comparison (relational) < > <= >= Yes
Equality == != === !== == and != only
Logical && || ! ?? Truthiness check, no conversion of the returned value
Unary +x -x typeof void +x and -x convert to Number
Assignment = += ??= Follows the underlying operator
Bitwise & | ^ ~ << Converts to 32-bit integer

Two things matter here. Operators are not the problem. The implicit conversion they trigger is.

How Type Coercion Works

JavaScript has two kinds of conversion:

  • Explicit coercion: you call Number(), String(), or Boolean().
  • Implicit coercion: the engine converts values for you during an operation.

Every implicit conversion routes through three abstract operations: ToPrimitive, ToNumber, and ToString. Objects pass through ToPrimitive first, which calls valueOf() and then toString().

Explicit Conversion Reference

// Explicit coercion: predictable and readable
console.log(Number("42"));      // 42
console.log(Number(""));        // 0
console.log(Number("  7  "));   // 7 (whitespace trimmed)
console.log(Number("12px"));    // NaN
console.log(Number(true));      // 1
console.log(Number(null));      // 0
console.log(Number(undefined)); // NaN
console.log(String(123));       // "123"
console.log(String(null));      // "null"
console.log(Boolean("0"));      // true (non-empty string)

Number() is strict about malformed input and returns NaN. parseInt(“12px”, 10) returns 12 because it parses until the first invalid character. Choose based on whether partial input is acceptable.

Truthy and Falsy Values

Exactly eight values are falsy:

// The complete falsy list
const falsyValues = [false, 0, -0, 0n, "", null, undefined, NaN];

falsyValues.forEach((v) => console.log(Boolean(v))); // false x8

// Everything else is truthy, including these surprises:
console.log(Boolean("0"));    // true
console.log(Boolean("false")); // true
console.log(Boolean([]));      // true
console.log(Boolean({}));      // true

Empty arrays and objects are truthy. This matters because == does not use truthiness. That mismatch causes the [] == false confusion covered below.

The + Operator: Concatenation vs. Addition

The + operator is the only arithmetic operator with dual behavior. After ToPrimitive, if either operand is a string, it concatenates. Otherwise it adds numerically.

console.log(1 + 2);        // 3
console.log("1" + 2);      // "12" (string wins)
console.log(1 + "2");      // "12"
console.log("3" - 1);      // 2   (- always converts to Number)
console.log("3" * "4");    // 12
console.log(true + 1);     // 2   (true -> 1)
console.log(null + 1);     // 1   (null -> 0)
console.log(undefined + 1); // NaN (undefined -> NaN)
console.log([] + []);      // ""  (both become "")
console.log([] + {});      // "[object Object]"

The -, *, /, and % operators have no string mode, so they always convert both sides to Number. Only + can switch to string mode, and that is why "3" + 1 and "3" - 1 give different types.

== vs ===: The Core Difference

Strict Equality (===)

=== returns false immediately if the types differ. If the types match, it compares values. There is no step three.

console.log(5 === 5);        // true
console.log(5 === "5");      // false (number vs string)
console.log("a" === "a");    // true
console.log(null === undefined); // false
console.log(NaN === NaN);    // false (the only value not equal to itself)

const a = { id: 1 };
const b = { id: 1 };
console.log(a === b);        // false (different references)
console.log(a === a);        // true  (same reference)

Objects, arrays, and functions compare by reference identity, not by contents.

Loose Equality (==) Algorithm

When types differ, == follows these rules, in order:

Step Condition Action
1 Same type Behave exactly like ===
2 null vs undefined Return true
3 Number vs String Convert the string to Number
4 BigInt vs String Convert the string to BigInt, then compare
5 Boolean vs anything Convert the Boolean to Number (true = 1, false = 0), then restart
6 Object vs primitive Apply ToPrimitive to the object, then restart
7 BigInt vs Number Compare mathematical values
8 Anything else Return false

Rule 5 explains most of the “WTF JavaScript” examples.

// Number vs String: string becomes a number
console.log(5 == "5");        // true
console.log(0 == "");         // true  ("" -> 0)
console.log(0 == " \n");      // true  (whitespace-only -> 0)

// Boolean converts to Number first
console.log(true == 1);       // true
console.log("1" == true);     // true  (true -> 1, "1" -> 1)
console.log("true" == true);  // false ("true" -> NaN, true -> 1)

// null and undefined equal only each other
console.log(null == undefined); // true
console.log(null == 0);         // false
console.log(null == false);     // false

Walking Through the Famous Puzzles

console.log([] == false);  // true
console.log([] == ![]);    // true

Trace [] == false:

  1. false is a Boolean, so it becomes 0. Now it reads [] == 0.
  2. [] is an object, so ToPrimitive gives "" (via toString()). Now it reads "" == 0.
  3. The string becomes a Number: 0 == 0, which is true.

Trace [] == ![]: the ! operator uses truthiness. [] is truthy, so ![] is false. The expression becomes [] == false, which is true by the steps above.

The array [] is truthy in an if check yet loosely equal to false. The two checks use different algorithms.

Relational Operators and the null Trap

Comparison operators (<, >, <=, >=) convert operands to Number unless both are strings. Two strings compare lexicographically by UTF-16 code units.

console.log(10 > 9);       // true
console.log("10" > "9");   // false (compares "1" vs "9" character-wise)
console.log("10" > 9);     // true  ("10" -> 10)
console.log("abc" > 5);    // false ("abc" -> NaN; any NaN comparison is false)

The null case breaks the assumption that == and >= share logic:

console.log(null == 0);  // false (== has a special rule for null)
console.log(null > 0);   // false (null -> 0, so 0 > 0 is false)
console.log(null >= 0);  // true  (null -> 0, so 0 >= 0 is true)

Relational operators coerce null to 0. Loose equality does not. The result is null >= 0 and null <= 0 both being true while null == 0 is false.

NaN, Object.is(), and SameValueZero

NaN is the only JavaScript value not equal to itself. Detect it with Number.isNaN(), not the global isNaN(), which coerces first.

console.log(isNaN("hello"));        // true  (coerces "hello" -> NaN)
console.log(Number.isNaN("hello")); // false (not a Number type)
console.log(Number.isNaN(NaN));     // true

// Object.is: SameValue algorithm
console.log(Object.is(NaN, NaN));   // true
console.log(Object.is(0, -0));      // false
console.log(0 === -0);              // true

// Array search methods differ
console.log([NaN].indexOf(NaN));    // -1 (uses ===)
console.log([NaN].includes(NaN));   // true (uses SameValueZero)

Use Object.is() when the difference between +0 and -0 or the identity of NaN matters. Array.prototype.includes() finds NaN, but indexOf() does not.

Logical Operators Return Operands, Not Booleans

&& and || return one of their operands. ?? (nullish coalescing) fixes a long-standing problem with || defaults.

console.log(0 || "default");     // "default" (0 is falsy)
console.log(0 ?? "default");     // 0         (0 is not nullish)
console.log("" || "fallback");   // "fallback"
console.log("" ?? "fallback");   // ""
console.log(null ?? "fallback"); // "fallback"
console.log(user && user.name);  // short-circuits if user is falsy

|| replaces any falsy value. ?? replaces only null and undefined. For a numeric config like port = 0, ?? is the correct operator.

Edge Cases That Throw Instead of Coercing

Not every mismatch converts quietly. Some throw a TypeError.

// Symbol cannot be implicitly converted
try {
  console.log(Symbol("id") + "");
} catch (e) {
  console.log(e.constructor.name); // "TypeError"
}

// BigInt cannot mix with Number in arithmetic
try {
  console.log(1n + 1);
} catch (e) {
  console.log(e.constructor.name); // "TypeError"
}

// But BigInt can be compared loosely
console.log(1n == 1);   // true
console.log(1n === 1);  // false (different types)
console.log(2n > 1);    // true

Arithmetic across BigInt and Number throws. Equality and relational comparison do not.

Refactoring: Bad Code vs. Good Code

Anti-Pattern: Relying on Loose Equality

// BAD: ambiguous, coercion-dependent
function validateAge(age) {
  if (age == "") return false;     // true for 0, "", " ", and [] too
  if (age == null) return false;   // intentional? hard to tell
  if (age == true) return false;   // true when age is 1 (or "1")
  return age > 17;
}

console.log(validateAge(0));  // false, but for the wrong reason

Here age == "" treats 0 as empty, which silently rejects a legitimate value.

Refactored: Explicit Types and Strict Checks

// GOOD: explicit conversion, strict comparison
function validateAge(input) {
  // Reject null and undefined in one explicit check
  if (input === null || input === undefined) return false;

  // Convert once, in one place
  const age = typeof input === "number" ? input : Number(input);

  // Guard against NaN and non-finite values
  if (!Number.isFinite(age)) return false;

  return age >= 18;
}

console.log(validateAge("21"));   // true
console.log(validateAge(0));      // false (valid number, too young)
console.log(validateAge(""));     // false (Number("") is 0, which is < 18)
console.log(validateAge("abc"));  // false (NaN rejected)
console.log(validateAge(null));   // false

The refactored version converts exactly once, rejects NaN explicitly, and uses === for the null check. Each branch states its intent.

The One Accepted Use of ==

// Idiomatic: checks for both null and undefined
if (value == null) {
  // value is null or undefined
}

// Equivalent, more verbose:
if (value === null || value === undefined) {
  // same result
}

value == null is the single widely accepted use of loose equality. In ESLint, the eqeqeq rule with the "smart" option permits it and flags everything else.

Performance Considerations

When both operands share a type, == and === behave identically, and modern engines like V8 optimize both to the same machine path. Mixed-type == adds a conversion step, but the cost is negligible next to DOM access or network calls. Choose between them for correctness, not speed.

Factor == ===
Same-type speed Equivalent Equivalent
Mixed-type cost Extra conversion Short-circuits to false
Bug risk High Low
Readability Requires rule knowledge Self-explanatory
Linter default Flagged Preferred

Practical Decision Guide

Situation Use
General comparison ===
Check for null or undefined value == null or ??
Detect NaN Number.isNaN(x)
Distinguish +0 from -0 Object.is()
Search an array for NaN .includes()
Parse user input Explicit Number() first, then ===
Default for falsy-but-valid values ??, not ||

Enable eqeqeq in ESLint and add TypeScript for type safety. TypeScript rejects many comparisons between unrelated types at compile time, which removes the most common coercion bugs before runtime.

FAQ

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

== converts operands to a common type before comparing. === compares type and value without conversion. So 5 == "5" is true, while 5 === "5" is false.

Why is [] == false true in JavaScript?

false becomes 0, then [] becomes "" through ToPrimitive, then "" becomes 0. The final comparison, 0 == 0, is true. Meanwhile [] is truthy in an if statement, because truthiness and loose equality use separate algorithms.

Should I always use === instead of ==?

Use === by default. The only widely accepted exception is value == null, which matches both null and undefined. Enforce the rule with ESLint’s eqeqeq setting.

Why does null >= 0 return true but null == 0 return false?

Relational operators (>=) convert null to 0. The == operator has a dedicated rule that makes null equal only to undefined (and itself). The two operators follow different paths.

Hot this week

Memory Management Across Languages: C++, Java, Python, and JavaScript

Compare manual allocation, garbage collection, and reference counting in C++, Java, Python, and JavaScript. See code and fix leaks today.

Common Python Beginner Mistakes (and How to Avoid Them)

Avoid the 10 most common Python beginner mistakes, from mutable defaults to bare except. Learn the fixes with code examples and start coding cleaner.

Dart Null Safety, Records, and Pattern Matching Explained

Master Dart 3 null safety, records, and pattern matching with production-ready code, comparison tables, and refactors. Start writing safer Dart today.

Your First Java Program: Hello World With Modern Java

Write your first Java Hello World in Java 25. Compare classic and compact versions, run code with one command, and fix common errors. Start coding now.

std::print and std::format: Modern C++ Output

Learn std::print and std::format in C++23: syntax, format specs, custom formatters, and migration from printf and iostream. Copy the examples now.

Topics

Memory Management Across Languages: C++, Java, Python, and JavaScript

Compare manual allocation, garbage collection, and reference counting in C++, Java, Python, and JavaScript. See code and fix leaks today.

Common Python Beginner Mistakes (and How to Avoid Them)

Avoid the 10 most common Python beginner mistakes, from mutable defaults to bare except. Learn the fixes with code examples and start coding cleaner.

Dart Null Safety, Records, and Pattern Matching Explained

Master Dart 3 null safety, records, and pattern matching with production-ready code, comparison tables, and refactors. Start writing safer Dart today.

Your First Java Program: Hello World With Modern Java

Write your first Java Hello World in Java 25. Compare classic and compact versions, run code with one command, and fix common errors. Start coding now.

std::print and std::format: Modern C++ Output

Learn std::print and std::format in C++23: syntax, format specs, custom formatters, and migration from printf and iostream. Copy the examples now.

Value Types vs Reference Types in C#: A Visual Guide

Learn how C# value types and reference types differ in memory, copying, and equality. Stack vs heap diagrams and code examples. Read the guide.

JavaScript Data Types: Primitives, Objects, and typeof

Learn all 8 JavaScript data types, how primitives differ from objects, and how typeof works, with code examples. Read the full guide now.

Variables in JavaScript: let, const, and Why var Is Legacy

Learn how let, const, and var differ in JavaScript: scope, hoisting, and the TDZ. See why var is legacy and refactor your code today.

Related Articles

Popular Categories