Data Types & Type Coercion
20 min read
PrimitivesReference TypesType Coercion== vs ===Falsy ValuestypeofNaN
JavaScript's Type System
JavaScript is dynamically typed — variables don't have fixed types. There are 7 primitive types and 1 structural type.
Primitive vs Reference Types
| Primitives (Immutable) | Reference (Mutable) |
|---|---|
string | Object |
number | Array |
bigint | Function |
boolean | Map / Set |
undefined | Date / RegExp |
null | |
symbol |
The typeof Operator Quirks
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" ← FAMOUS BUG (since 1995!)
typeof [] // "object" ← Arrays are objects
typeof function(){} // "function"Type Coercion: == vs ===
== performs type coercion (converts types before comparing). === checks value AND type (strict equality).
| Expression | == | === | Why |
|---|---|---|---|
0 == "" | true | false | Both coerce to 0 |
0 == "0" | true | false | "0" → 0 |
"" == "0" | false | false | Different strings |
null == undefined | true | false | Special rule in spec |
NaN == NaN | false | false | NaN ≠ anything |
Falsy Values (All 8)
// These are ALL the falsy values in JS:
false, 0, -0, 0n, "", null, undefined, NaN
// Everything else is truthy, including:
// "0", "false", [], {}, function(){}Implicit Coercion Traps
console.log(1 + "2"); // "12" (number → string)
console.log("6" - 1); // 5 (string → number)
console.log(true + true); // 2 (boolean → number)
console.log([] + []); // "" (arrays → strings → concat)
console.log({} + []); // "[object Object]" or 0
console.log([] + {}); // "[object Object]"Safe Type Checking
// Use these instead of typeof for edge cases:
Array.isArray([]); // true
Number.isNaN(NaN); // true (not global isNaN!)
Number.isFinite(42); // true
Object.prototype.toString.call(null); // "[object Null]"