Skip to content

Types and Coercion

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 copy
let a = 42;
let b = a;
b = 99;
console.log(a); // 42 — unchanged
// Objects: both variables point to the same object
const x = { count: 0 };
const y = x;
y.count = 5;
console.log(x.count); // 5 — same object

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 fixable
typeof {} // 'object'
typeof [] // 'object' ← arrays are objects
typeof 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.

== performs type coercion before comparing. === does not — it checks both value and type.

0 == false // true — false coerces to 0
0 === false // false — number vs boolean
'' == false // true — both coerce to 0
'' === false // false
null == undefined // true — special rule
null === undefined // false
1 == '1' // true — '1' coerces to 1
1 === '1' // false

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'); // prints
if ({}) console.log('empty object is truthy'); // prints
if (0) console.log('zero is truthy'); // does NOT print
// Spot the coercion surprises
console.log(0 == false); // true
console.log(0 === false); // false
console.log(null == undefined); // true
console.log(null === undefined); // false
console.log([] == false); // true — [] coerces to '' coerces to 0
console.log(Boolean([])); // true — [] is truthy!
console.log(typeof null); // object
JavaScript
What does `typeof null` return in JavaScript?
Which of these values is falsy?
What is the result of `null == undefined`?