Type coercion

Topic 5 of 5 in Variables & types7 min readBeginnerFree course

Overview

When an operation gets values of different types, JavaScript quietly converts one of them so it can carry on. This is called coercion (or implicit type conversion). It’s convenient — 'Total: ' + 5 just works — but it can also hide bugs, especially with values that come from forms and URLs, which are always strings.

The good news: coercion follows a small number of rules, and you can avoid almost all surprises by converting values on purpose.

Implicit conversion

JavaScript
'5' + 1;   // '51' — the number becomes a string
'5' - 1;   // 4    — the string becomes a number
'3' * '2'; // 6
'10' / 2;  // 5
'abc' * 2; // NaN  — 'abc' can't become a number

The + operator is the tricky one, because it does two jobs: adding numbers and joining strings. If either side is a string, it joins rather than adds. All the other arithmetic operators (-, *, /, %, **) only work on numbers, so they always convert to numbers.

A flowchart for a + b: if either side is a string, the values are joined as text, so ‘5’ + 1 gives ‘51’. Otherwise they are added as numbers, so 1 + true gives 2. Minus, times, divide and remainder always convert to numbers. Beside it, the six falsy values — false, 0, empty string, null, undefined, NaN — and examples of truthy values, including ‘0’, ‘false’, an empty array and an empty object.

Order matters too, because + works left to right:

JavaScript
1 + 2 + '3';  // '33' — 1 + 2 = 3, then 3 + '3' = '33'
'1' + 2 + 3;  // '123'

A real-world bug

Input fields always give you strings. This looks right but isn’t:

JavaScript
const qty = document.querySelector('#qty').value; // '2'
const total = qty + 1; // '21' — not 3!

The fix is to convert as soon as the value enters your program:

JavaScript
const qty = Number(document.querySelector('#qty').value);
const total = qty + 1; // 3

Equality

== (loose equality) converts types before comparing; === (strict equality) doesn’t — values of different types are simply not equal.

JavaScript
0 == false;          // true
0 === false;         // false
'' == 0;             // true
'1' == 1;            // true
'1' === 1;           // false
null == undefined;   // true
null === undefined;  // false

The conversion rules for == are long and full of oddities — '' == 0 and '0' == 0 are both true, but '' == '0' is false. You don’t need to memorise them.

Rule of thumb: always use === and !==. Your comparisons then mean exactly what they say. The one common exception some teams allow is value == null, which is true for both null and undefined.

Converting on purpose

Explicit conversion makes your intent obvious to readers and avoids surprises:

JavaScript
Number('42');     // 42
Number('4.5');    // 4.5
Number('');       // 0   ← careful with empty inputs
Number(' 12 ');   // 12  (surrounding spaces are ignored)
Number('12px');   // NaN
Number(true);     // 1
Number(null);     // 0
Number(undefined);// NaN

String(42);       // '42'
String(null);     // 'null'
(42).toString();  // '42'

Boolean('');      // false
Boolean('hello'); // true
Boolean(0);       // false

Shorthand conversions

You’ll see these in other people’s code. They work, but the long forms above are clearer:

JavaScript
+'42';    // 42      — unary plus converts to a number
'' + 42;  // '42'    — adding an empty string converts to a string
!!'hi';   // true    — double NOT converts to a boolean

Truthy and falsy

In an if, a loop condition, or with &&, || and !, every value is treated as either true or false. There are exactly six falsy values:

JavaScript
false
0        // (and -0 and 0n)
''       // empty string
null
undefined
NaN

Everything else is truthy — including some values that look empty or false:

JavaScript
if ('0')     { /* runs — a non-empty string */ }
if ('false') { /* runs */ }
if ([])      { /* runs — an empty array is still an object */ }
if ({})      { /* runs */ }

Truthiness gives you neat checks:

JavaScript
if (name) {
  console.log(`Hi ${name}`); // only if name isn't empty, null or undefined
}

But it can catch you out when 0 or '' are valid values:

JavaScript
const stock = 0;
if (!stock) {
  console.log('Missing stock value'); // runs — but 0 is a real value!
}

// Be specific instead:
if (stock === undefined) { /* … */ }

To check an array or string is empty, compare its length: if (items.length === 0).

Objects and coercion

When an object meets + or a template literal, JavaScript turns it into a string — and plain objects become the unhelpful '[object Object]':

JavaScript
const user = { name: 'Asha' };
'User: ' + user;       // 'User: [object Object]'
`User: ${user.name}`;  // 'User: Asha'
[1, 2] + '';           // '1,2' — arrays join their items with commas

If you ever see [object Object] on a page, it means an object was coerced to a string by accident. Use a specific property, or JSON.stringify(user) while debugging.

Exercise

Predict the result

Work out what each line prints before running it. Then fix addToCart so that addToCart('2', 3) returns 5, not '23'.

JavaScript
console.log('5' + 1);
console.log('5' - 1);
console.log(0 == false);
console.log(0 === false);
console.log(Boolean('0'));

function addToCart(current, extra) {
  return current + extra;
}

Summary

  • + joins strings if either side is a string; other maths operators convert to numbers.
  • Prefer === and !==, which never convert types.
  • Convert on purpose with Number(), String() and Boolean().
  • The six falsy values are false, 0, '', null, undefined and NaN — everything else is truthy.
  • '0', 'false', [] and {} are all truthy.