Last updated
Data Type Conversion
Data type conversion transforms values from one type to another. In programming, this is either implicit (automatic coercion) or explicit (casting). JavaScript is notorious for implicit type coercion, which can cause unexpected behavior. Understanding type conversion rules is essential for writing correct code.
JavaScript Type Coercion Rules
| Expression | Result | Reason |
|---|---|---|
"5" + 3 | "53" | + with string = concatenation |
"5" - 3 | 2 | - converts string to number |
null + 1 | 1 | null coerces to 0 |
undefined + 1 | NaN | undefined coerces to NaN |
[] + [] | "" | arrays coerce to empty strings |
[] + {} | "[object Object]" | object toString |
false == 0 | true | loose equality coercion |
Safe Type Conversion in JavaScript
JavaScript
// String to number (safe)
const n = Number('42'); // 42
const n2 = parseInt('42px'); // 42 (stops at non-digit)
const n3 = parseFloat('3.14'); // 3.14
// Number to string
const s = String(42); // '42'
const s2 = (42).toString(16); // '2a' (hex)
const s3 = (42).toString(2); // '101010' (binary)
// Boolean conversion
Boolean(0); // false
Boolean(''); // false
Boolean(null); // false
Boolean(undefined); // false
Boolean(NaN); // false
Boolean([]); // true (empty array is truthy!)
Boolean({}); // true (empty object is truthy!)