Skip to main content

JavaScript Data Types

Primitive Types (7)

Primitives are immutable and stored on the stack.

TypeExampletypeof
string"hello""string"
number42, 3.14, NaN, Infinity"number"
bigint9007199254740991n"bigint"
booleantrue, false"boolean"
undefinedundefined"undefined"
nullnull"object" ⚠️ (bug)
symbolSymbol("id")"symbol"

Non-Primitive (Reference) Types

Reference types are stored on the heap.

  • Object{}, arrays, functions, dates, regex, etc.
typeof {};           // "object"
typeof []; // "object" — arrays are objects
typeof function(){}; // "function"
typeof null; // "object" — historical bug in JS

Type Coercion

Implicit Coercion

"5" + 3;      // "53"  — number coerced to string
"5" - 3; // 2 — string coerced to number
true + 1; // 2 — true becomes 1
false + 1; // 1 — false becomes 0
null + 5; // 5 — null becomes 0
undefined + 5; // NaN — undefined becomes NaN

Explicit Coercion

Number("42");     // 42
String(42); // "42"
Boolean(0); // false
Boolean(""); // false
Boolean("hello"); // true
parseInt("42px"); // 42

Falsy Values

These are the only 8 falsy values in JavaScript:

false, 0, -0, 0n, "", null, undefined, NaN

Everything else is truthy (including [], {}, "0", "false").

== vs ===

0 == false;    // true  — type coercion happens
0 === false; // false — no coercion, different types
null == undefined; // true
null === undefined; // false

Rule: Always use === unless you specifically need type coercion.

Checking Types

// typeof — works for primitives
typeof "hello"; // "string"

// instanceof — works for objects
[] instanceof Array; // true

// Array.isArray — best for arrays
Array.isArray([]); // true
Array.isArray({}); // false

// Object.prototype.toString — most reliable
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(null); // "[object Null]"

Key Takeaways

  • 7 primitive types + 1 reference type (Object).
  • typeof null === "object" is a known JS bug.
  • Use === over == to avoid unexpected coercion.
  • Know all 8 falsy values — everything else is truthy.