Learn the concept
Type Coercion
Type coercion is JavaScript's automatic conversion of values from one type to another. It happens implicitly with operators like +, ==, and if(), or explicitly using Number(), String(), and Boolean().
JavaScript is a dynamically typed language that automatically converts types when needed.
Implicit coercion (automatic):
+ with a string converts the other operand to string-, *, /, >, < convert to numbersif(), &&, ||, ! convert to booleanExplicit coercion (intentional):
Number(value), parseInt(), parseFloat()String(value), .toString()Boolean(value), !!valueFalsy values (convert to false):
false, 0, -0, 0n, "", null, undefined, NaN
Everything else is truthy, including [], {}, and "0".
// String coercion with +
'5' + 3 // '53' (number → string)
'5' + true // '5true'
'5' + null // '5null'
// Numeric coercion with -, *, /
'5' - 3 // 2 (string → number)
'5' * '2' // 10
true + true // 2 (boolean → number)
// Boolean coercion
if ('hello') {} // true (non-empty string)
if (0) {} // false
if ([]) {} // true (empty array is truthy!)
if ({}) {} // true (empty object is truthy!)
// Common gotchas
[] + [] // '' (empty string)
[] + {} // '[object Object]'
{} + [] // 0 (in console; as expression: '[object Object]')
null + 1 // 1
undefined + 1 // NaNConverting string inputs to numbers for calculations using explicit coercion like Number(input.value)
Using truthy/falsy checks like value || 'default' for setting fallback values in function parameters
Ensuring correct types when processing JSON responses where numbers may arrive as strings
Build an interactive game testing knowledge of coercion results for various JavaScript expressions
Build a tool that generates a complete equality and coercion table for all JavaScript type combinations