Types and Coercion
Primitives vs objects
Section titled “Primitives vs objects”JavaScript has two categories of values:
Primitives — immutable, stored by value:
string,number,bigint,boolean,undefined,null,symbol
Objects — mutable, stored by reference:
- Plain objects
{}, arrays[], functions,Map,Set,Date, etc.
// Primitives: each variable holds an independent copylet a = 42;let b = a;b = 99;console.log(a); // 42 — unchanged
// Objects: both variables point to the same objectconst x = { count: 0 };const y = x;y.count = 5;console.log(x.count); // 5 — same objecttypeof
Section titled “typeof”typeof returns a string describing the type of a value. A few results are surprising:
typeof 42 // 'number'typeof 'hello' // 'string'typeof true // 'boolean'typeof undefined // 'undefined'typeof null // 'object' ← historical bug, not fixabletypeof {} // 'object'typeof [] // 'object' ← arrays are objectstypeof function(){} // 'function'typeof Symbol() // 'symbol'typeof 9007n // 'bigint'The typeof null === 'object' quirk has been in the spec since JavaScript 1.0. To check for null specifically, use value === null.
== vs ===
Section titled “== vs ===”== performs type coercion before comparing. === does not — it checks both value and type.
0 == false // true — false coerces to 00 === false // false — number vs boolean
'' == false // true — both coerce to 0'' === false // false
null == undefined // true — special rulenull === undefined // false
1 == '1' // true — '1' coerces to 11 === '1' // falseTruthy and falsy
Section titled “Truthy and falsy”Every value is either truthy or falsy when used in a boolean context.
Falsy values — only these six:
false,0,''(empty string),null,undefined,NaN
Everything else is truthy — including [], {}, '0', and 'false'.
if ([]) console.log('empty array is truthy'); // printsif ({}) console.log('empty object is truthy'); // printsif (0) console.log('zero is truthy'); // does NOT printRunnable coercion demo
Section titled “Runnable coercion demo”// Spot the coercion surprisesconsole.log(0 == false); // trueconsole.log(0 === false); // falseconsole.log(null == undefined); // trueconsole.log(null === undefined); // falseconsole.log([] == false); // true — [] coerces to '' coerces to 0console.log(Boolean([])); // true — [] is truthy!console.log(typeof null); // object