Implicit Type Coercion and == in JavaScript: The Rules Behind the Surprises
Why "3" - 1 is 2 but "3" + 1 is "31", how +, arithmetic, comparison and == coerce their operands, the loose equality algorithm step by step (and why [] == ![] is true), when == is acceptable, and how to keep coercion from biting you.
kvi5hnuCode Sprout team member7 min readOn this page
JavaScript rarely refuses an operation because of mismatched types. Instead it coerces: it converts one or both operands to the types the operator needs, using the conversion rules from article 22. This is why so many "JavaScript is weird" memes exist, like [] + {}, "b" + "a" + +"a" + "a" and [] == ![]. None of them are random. Each follows a small set of rules, and once you know the rules you can predict every case, and avoid the dangerous ones.
Which operators coerce to what
| Operator | Converts operands to | Example |
|---|---|---|
-, *, /, %, **, unary - and + | numbers | "6" / "2" is 3 |
+ (binary) | strings if either side is a string, otherwise numbers | "6" + 2 is "62" |
<, >, <=, >= | numbers, unless both are strings (then compared as text) | "10" < 9 is false |
==, != | the loose equality algorithm (below) | "1" == 1 is true |
&&, ||, !, if, ?:, while | booleans (for the test) | if ("0") runs |
template literals, String() | strings | `${7}` is "7" |
bitwise |, &, ^, ~, <<, >>, >>> | 32-bit integers | "7.9" | 0 is 7 |
Arithmetic: everything becomes a number
Except for +, the arithmetic operators always convert to numbers:
console.log("3" - 1, "3" * "4", "10" / "4", "7" % 2);
console.log(true + 1, null + 1, undefined + 1); // 2, 1, NaN
console.log([5] * 2, [] - 1, "a" * 1); // arrays via their string form
console.log(-"5", +"", +" 42 "); // unary minus and plus
2 12 2.5 1
2 1 NaN
10 -1 NaN
-5 0 42
null becomes 0 and undefined becomes NaN, so a missing value either silently becomes zero or poisons the result.
The + operator: strings win
Binary + adds numbers or concatenates strings. The rule:
- Convert both operands to primitives (objects use their
valueOf/toString, article 24). - If either primitive is a string, convert the other to a string and concatenate.
- Otherwise, convert both to numbers and add.
console.log(1 + "2", "1" + 2); // a string anywhere means concatenation
console.log(1 + 2 + "3", "1" + 2 + 3); // evaluated left to right
console.log(true + "!", null + "!");
console.log([1, 2] + [3]); // arrays become strings first
console.log([] + []); // "" + "" is ""
console.log([] + {}); // "" + "[object Object]"
console.log("b" + "a" + +"a" + "a"); // the famous meme
12 12
33 123
true! null!
1,23
[object Object]
baNaNa
Left-to-right evaluation explains 1 + 2 + "3": first 1 + 2 is 3, then 3 + "3" is "33". And the banana: +"a" is unary plus, which converts "a" to NaN, and "ba" + NaN is "baNaN".
The practical danger is adding values that you think are numbers but are strings, such as form inputs, URL parameters or localStorage values:
const quantityField = "2"; // input values are always strings
const total = quantityField + 1; // concatenation, not addition
console.log(total);
console.log(Number(quantityField) + 1);
21
3
Convert input explicitly at the boundary (article 22), and these bugs disappear.
Relational comparison: <, >, <=, >=
Relational operators convert objects to primitives, then:
- if both are strings, compare them as text, code unit by code unit (article 14);
- otherwise convert both to numbers (or compare bigint values) and compare numerically. Any
NaNmakes the resultfalse.
console.log("10" < "9"); // both strings: "1" sorts before "9"
console.log("10" < 9); // mixed: compared as numbers
console.log("abc" < "abd");
console.log(null >= 0, null > 0, undefined >= 0); // null → 0, undefined → NaN
console.log("a" < 1, "a" >= 1); // NaN: both false
console.log(new Date(5) > new Date(1)); // dates compare by timestamp
true
false
true
true false false
false false
true
The string comparison catches people when sorting or comparing numeric strings, such as version numbers or values read from a file: "10" < "9" is true. Convert to numbers first.
The == algorithm
=== (strict equality) never converts: different types are simply not equal. == (loose equality) converts first, following these steps:
![The loose equality algorithm in seven steps, with [] == false worked through](https://code-sprout-content.laxmi.solutions/asset/2026/11/js-loose-equality-algorithm-ytsgzxtzixrw73q4.png)
- Same type: compare like
===. nullandundefinedare equal to each other and to nothing else.- A boolean is converted to a number (1 or 0), then compare again.
- An object compared with a primitive is converted to a primitive, then compare again.
- Number and string: the string is converted to a number.
- BigInt with number or string: the mathematical values are compared.
- Anything else is
false.
console.log(null == undefined, null == 0, undefined == ""); // step 2
console.log("1" == 1, "" == 0, " \n" == 0); // step 5
console.log("1" == true, "2" == true, "0" == false); // step 3, then 5
console.log([1] == 1, [1, 2] == "1,2", [] == ""); // step 4
console.log(NaN == NaN, 1n == 1, 1n == "1"); // steps 1 and 6
true false false
true true true
true false true
true true true
false true true
Notice step 3. A boolean is not compared by truthiness: "2" == true becomes "2" == 1, then 2 == 1, which is false, even though "2" is truthy. Comparing anything to true or false with == is almost always a mistake.
Now the most famous puzzle:
console.log(![]); // [] is truthy, so ![] is false
console.log([] == false); // [] == 0 → "" == 0 → 0 == 0
console.log([] == ![]);
false
true
true
The ! applies first (![] is false), and then [] == false follows steps 3, 4 and 5 down to 0 == 0. So an array is equal to its own negation, while also being truthy. This is the clearest argument for ===.
When is == acceptable?
The common, widely accepted rule: use === and !== everywhere, with one exception: x == null (and x != null), which is a concise check for "null or undefined" (step 2 guarantees nothing else matches).
ESLint's eqeqeq rule enforces this; its "smart" option or { "null": "ignore" } allows the == null exception. With TypeScript, many == problems become type errors anyway.
Hidden coercions to watch for
Coercion also happens in places that aren't operators:
const scores = { 1: "first" };
console.log(scores[1] === scores["1"]); // property keys are converted to strings
console.log([10, 9, 1].sort()); // default sort converts to strings!
console.log([10, 9, 1].sort((a, b) => a - b));
console.log(isNaN("hello"), Number.isNaN("hello")); // the global isNaN coerces
console.log(Math.max("7", 3)); // Math functions coerce to numbers
console.log(new Set([1, "1"]).size); // but Set and Map do NOT coerce keys
true
[ 1, 10, 9 ]
[ 1, 9, 10 ]
true false
7
2
The default sort() is one of the most common real-world coercion bugs: without a comparator it sorts numbers as strings, so 10 comes before 9.
Staying safe
- Use
===, except for the== nullcheck. - Convert explicitly at the boundaries: when reading input, query strings, JSON, files or storage, turn values into the types you expect, once.
- Use template literals for building strings instead of mixing
+with numbers. - Pass a comparator to
sortfor anything but plain strings. - Let tools help: ESLint (
eqeqeq,no-implicit-coercion) and TypeScript catch most accidental coercions before they run.
Common questions
Is == faster or slower than ===?
=== can't be slower, since it skips conversion, but the difference is negligible. Choose for correctness, not speed.
Why is null >= 0 true but null == 0 false?
Relational operators convert null to a number (0), so null >= 0 is 0 >= 0. But == has a dedicated rule (step 2): null equals only null and undefined. The two operators use different algorithms.
Does if (x == true) work like if (x)?
No. if (x) tests truthiness, while x == true converts true to 1 and compares. So for x = "yes", if (x) runs but x == true is false. Write if (x) or, if you really need exactly true, if (x === true).
Why does "5" * "2" work but "5" + "2" gives "52"?
* only means multiplication, so it converts both strings to numbers. + also means string concatenation, and when either operand is a string, concatenation wins.
Summary
- Arithmetic operators other than
+convert to numbers;null→ 0,undefined→ NaN. +concatenates if either operand (after conversion to a primitive) is a string; it's evaluated left to right.<and friends compare as text when both operands are strings, otherwise as numbers; NaN makes them false.==follows a fixed algorithm: same type →===; null/undefined only equal each other; booleans become numbers; objects become primitives; strings become numbers.[] == ![]is true because![]isfalse, and[] == falsereduces to0 == 0.- Use
===(plus== null), convert at the boundaries, and let ESLint and TypeScript flag the rest.
Practice Questions
What do "4" + 2, "4" - 2 and "4" * "2" evaluate to?
Answer
"42", 2 and 8.
Evaluate [] + null + 1.
Answer
"null1". [] becomes "", "" + null is "null", and "null" + 1 is "null1".
Which are true: 0 == "", 0 == "0", "" == "0"?
Answer
The first two. 0 == "" and 0 == "0" both convert the string to the number 0. But "" == "0" compares two strings of the same type, which differ. So == isn't even transitive.
Why does [2, 10, 1].sort() return [1, 10, 2]?
Answer
Without a comparator, sort converts elements to strings and compares them as text: "1" < "10" < "2". Use .sort((a, b) => a - b).
What's the safest one-line check that a value is neither null nor undefined?
Answer
value != null. By the == rules, only null and undefined are loosely equal to null.
Previous: JavaScript Type Conversion: String(), Number(), Boolean(), parseInt and Formatting Numbers
Next: Object-to-Primitive Conversion in JavaScript: valueOf, toString and Symbol.toPrimitive

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.