← JavaScript

Basic · 9 of 12 · 12 min read

Type coercion

Why + behaves differently from every other operator, what == does before it compares, and the handful of conversions worth memorising.

  • Type coercion
  • Equality

Coercion is JavaScript converting a value to another type so an operation can proceed. It is not random — there are a small number of rules, and once you know which operator triggers which one, the “weird JavaScript” snippets stop being surprising.

Explicit conversion

Do this on purpose and most of the rest never comes up:

console.log(String(42), String(null), String([1, 2]));   // "42" "null" "1,2"
console.log(Number('42'), Number(''), Number('abc'));    // 42 0 NaN
console.log(Boolean(''), Boolean('0'), Boolean([]));     // false true true

console.log(parseInt('12px', 10));  // 12   — reads leading digits, stops
console.log(Number('12px'));        // NaN  — demands the whole string
console.log(parseFloat('1.5rem'));  // 1.5
console.log(+'42', +true, +'');     // 42 1 0   — unary plus is Number()

The Number rules worth memorising, because they are the ones that look arbitrary:

Input Number(…) Why
'' 0 trimmed to nothing, which the spec defines as 0
' ' 0 same
' 42 ' 42 trimmed, then parsed
'4 2' NaN not a numeric literal
null 0 special-cased
undefined NaN special-cased, differently
true / false 1 / 0
[] 0 joins to '', then '' → 0
[7] 7 joins to '7'
[1, 2] NaN joins to '1,2'
{} NaN stringifies to '[object Object]'
console.log(Number(''), Number(null), Number(undefined)); // 0 0 NaN
console.log(Number([]), Number([7]), Number([1, 2]));     // 0 7 NaN

+ has two jobs

If either side is a string, + concatenates. Otherwise it adds. And it is left-associative, so the order of operands matters:

console.log(1 + 2);         // 3     — both numbers
console.log(1 + '2');       // "12"  — one string wins
console.log('1' + 2);       // "12"
console.log(1 + 2 + '3');   // "33"  — (1+2) is 3, then "3" + "3"
console.log('1' + 2 + 3);   // "123" — "12" first, then "123"

console.log(1 + true);      // 2     — no string involved
console.log('' + 1 + 0);    // "10"
console.log([] + {});       // "[object Object]"

Every other arithmetic operator converts to numbers, because it has no string meaning:

console.log('5' - 2);  // 3
console.log('5' * 2);  // 10
console.log('5' / 2);  // 2.5
console.log('5' % 2);  // 1
console.log('5' ** 2); // 25
console.log('5' + 2);  // "52"  ← the odd one out

Which gives you the single most useful debugging habit here: if a number came out as a string, look for a +.

const quantity = '2'; // from an input field
console.log(quantity + 1); // "21"  ← the bug
console.log(+quantity + 1); // 3    ← the fix
console.log(Number(quantity) + 1); // 3  ← the clearer fix

Comparison coerces too

Relational operators convert to numbers — unless both sides are strings, in which case they compare lexicographically:

console.log('10' > 9);    // true   — "10" becomes 10
console.log('10' > '9');  // false  — both strings: "1" < "9" character by character
console.log('b' > 'a');   // true
console.log([] < 1);      // true   — [] becomes 0

That string case is why sorting numbers with the default comparator goes wrong:

console.log([10, 9, 1].sort());               // [1, 10, 9]
console.log([10, 9, 1].sort((a, b) => a - b)); // [1, 9, 10]

== versus ===

=== compares type and value with no conversion. == converts first, following a specific set of rules.

console.log(1 === 1, '1' === 1);  // true false
console.log(1 == 1, '1' == 1);    // true true

The == rules, in the order they apply:

Comparison Result Rule
null == undefined true special-cased
null == 0 false null is not converted to a number here
undefined == 0 false same
'1' == 1 true string → number
true == 1 true boolean → number
0 == false true boolean → number
'' == 0 true string → number, '' → 0
[] == 0 true array → '' → 0
[1] == 1 true array → '1' → 1
{} == {} false two objects, compared by reference
NaN == NaN false NaN equals nothing, including itself
console.log(null == undefined, null === undefined); // true false
console.log(null == 0, null >= 0);                  // false true  ← different operators, different rules
console.log('' == 0, [] == 0, [1] == 1);            // true true true
console.log(NaN == NaN, Number.isNaN(NaN));         // false true

null == 0 being false while null >= 0 is true is the sharpest edge in the language: == special-cases null, and the relational operators do not.

The [] == ![] puzzle

It looks absurd and it is just the rules applied in order:

console.log([] == ![]); // true
  1. ![] — an array is truthy, so this is false.
  2. [] == false — a boolean becomes a number: [] == 0.
  3. [] becomes a primitive via toString(): '' == 0.
  4. '' becomes a number: 0 == 0 → true.

Nobody writes this. The reason it is worth walking through is that every step is a rule you will meet in real code.

The one good use of ==

value == null is a compact, idiomatic test for “null or undefined”, and many style guides allow exactly that one exception:

function greet(name) {
  if (name == null) return 'Hi there'; // catches both
  return 'Hi ' + name;
}

console.log(greet(null), greet(undefined), greet('Ana')); // Hi there / Hi there / Hi Ana

Object.is, for the two edge cases

Identical to === except for NaN and -0:

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

// It is not a deep comparison, despite the name:
console.log(Object.is({ a: 1 }, { a: 1 }));    // false

How an object becomes a primitive

When an operator needs a primitive from an object, the engine tries valueOf() then toString() (or toString() first in a string context). That is why Date behaves differently from an array:

console.log([1, 2] + '');       // "1,2"           — toString
console.log({} + '');           // "[object Object]"
console.log(new Date() - 0);    // a timestamp     — valueOf gives a number
console.log(`${new Date(0)}`);  // a date string   — toString in a template literal

You can control it:

const money = {
  amount: 5,
  valueOf() { return this.amount; },
  toString() { return `$${this.amount}`; },
};

console.log(money + 1);    // 6      — numeric context
console.log(`${money}`);   // "$5"   — string context

Common mistakes

Doing arithmetic on form input

Mistake. total = price + quantity where both came out of inputs. Why it fails. DOM values are strings, and + concatenates them: "10" + "2" is "102". What to do instead. Convert at the boundary, once: Number(price) + Number(quantity), and validate with Number.isFinite while you are there.

if (value) to mean “has a value”

Mistake. Guarding with truthiness when 0 or '' is legitimate data. Why it fails. Both are falsy, so a real zero is treated as missing. What to do instead. value != null, or supply the default with ?? instead of ||.

Reaching for == to be forgiving

Mistake. Using == so that '1' and 1 match. Why it fails. You also get '' == 0, [] == 0 and [1] == 1, none of which you asked for. What to do instead. Convert explicitly, then compare with ===. Keep == null as the one deliberate exception.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

+ is the one operator in JavaScript with two different jobs, and it has to pick one.

What does this log?

Code sample
console.log(1 + "2");

Each arithmetic operator decides for itself what to do when one side is a string.

What does this log?

Code sample
console.log("5" - 2);

JavaScript has two equality operators and they disagree on purpose.

What does this log?

Code sample
console.log(0 == false);
console.log(0 === false);
Practise Type coercion and Equality →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.