Type coercion
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
'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 numberThe + 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.
Order matters too, because + works left to right:
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:
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:
const qty = Number(document.querySelector('#qty').value);
const total = qty + 1; // 3Equality
== (loose equality) converts types before comparing; === (strict equality) doesn’t — values of different types are simply not equal.
0 == false; // true
0 === false; // false
'' == 0; // true
'1' == 1; // true
'1' === 1; // false
null == undefined; // true
null === undefined; // falseThe 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 isvalue == null, which is true for bothnullandundefined.
Converting on purpose
Explicit conversion makes your intent obvious to readers and avoids surprises:
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); // falseShorthand conversions
You’ll see these in other people’s code. They work, but the long forms above are clearer:
+'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 booleanTruthy 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:
false
0 // (and -0 and 0n)
'' // empty string
null
undefined
NaNEverything else is truthy — including some values that look empty or false:
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:
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:
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]':
const user = { name: 'Asha' };
'User: ' + user; // 'User: [object Object]'
`User: ${user.name}`; // 'User: Asha'
[1, 2] + ''; // '1,2' — arrays join their items with commasIf 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.
Predict the result
Work out what each line prints before running it. Then fix addToCart so that addToCart('2', 3) returns 5, not '23'.
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;
}// '51', 4, true, false, true
function addToCart(current, extra) {
return Number(current) + Number(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()andBoolean(). - The six falsy values are
false,0,'',null,undefinedandNaN— everything else is truthy. '0','false',[]and{}are all truthy.