JavaScript by Example

Values

JavaScript has seven primitive types plus the object type - and one infamous typeof quirk.

JavaScript has eight value types: seven primitives (string, number, bigint, boolean, undefined, symbol, and null) and object. The typeof operator reveals a value's type - with one infamous exception.

Numbers, strings, and booleans are the most common primitives. typeof returns their type as a lowercase string.

typeof 42;         // "number"
typeof "hello";    // "string"
typeof true;       // "boolean"
typeof undefined;  // "undefined"
typeof Symbol();   // "symbol"
typeof 9007199254740993n; // "bigint"

null is technically a primitive, but typeof null returns "object" - a legacy bug in the language that can never be fixed without breaking existing code. Check for null explicitly.

typeof null;        // "object" - legacy quirk, not a real object
null === null;      // true  - use this instead
null !== undefined; // true  - null and undefined are distinct

Always use strict equality (===) for comparisons. The loose equality operator (==) coerces types before comparing, producing results that are rarely what you want.

0 == false;         // true  (type coercion)
0 === false;        // false (strict - different types)
 
"" == false;        // true  (coercion)
"" === false;       // false
 
null == undefined;  // true  (special case)
null === undefined; // false

In production

The typeof null === "object" quirk bites null checks written as if (typeof x === "object") - that check passes for null. Always combine it with an explicit x !== null guard, or just check x === null directly. Prefer strict equality (===) everywhere; the loose == operator has over a dozen coercion rules that produce surprises in feature-flag defaults, counter comparisons, and conditional rendering.

Enjoyed this? Get more essays on software craft delivered to your inbox.

Subscribe free