Skip to the page

Values, types and coercion · core

Primitives vs objects, typeof, null vs undefined

JavaScript has seven primitive types (string, number, bigint, boolean, undefined, symbol, null) that are immutable and compared by value; everything else is an object, held and compared by reference.

The notes

What you must know

  • The 7 primitives are string, number, bigint, boolean, undefined, symbol and null. Arrays, functions, dates and maps are all objects.
  • typeof null is "object" (an old bug kept for compatibility). typeof a function is "function". typeof an array is "object".
  • Primitives are immutable: 'abc'.toUpperCase() returns a new string. Objects are mutable and compared by identity, so {} === {} is false.
  • JavaScript always passes arguments by value. For an object the value is a reference, so mutating the object inside a function is visible outside, but reassigning the parameter is not.
  • undefined means 'no value yet' (unassigned variable, missing property, no return). null means 'empty on purpose'. An undeclared variable throws ReferenceError when read, except inside typeof, which returns "undefined".
  • Reliable checks: x === null, x == null (null or undefined), Array.isArray(x), typeof x === 'function', Number.isNaN(x), Object.prototype.toString.call(x) for built-in tags like [object Date].
  • Autoboxing: 'abc'.length works because the engine wraps the primitive in a temporary String object; a property you add to a primitive is lost immediately.

The red pen

Common traps: mistake → fix

  • Mistake: typeof null is 'null'

    Fix: it is 'object'; check null with === null.

  • Mistake: Objects are passed by reference

    Fix: the reference is copied by value; reassigning the parameter never changes the caller's variable.

  • Mistake: typeof [] is 'array'

    Fix: it is 'object'; use Array.isArray.

  • Mistake: null and undefined are the same

    Fix: null == undefined is true but null === undefined is false, and JSON.stringify keeps null but drops undefined properties.

Easy to hard

Questions interviewers ask, easy to hard

  1. What are the primitive types in JavaScript?
  2. Why is typeof null 'object'? How do you check for null, an array and a plain object?
  3. Is JavaScript pass-by-reference? Prove your answer with code.
  4. What is the difference between null, undefined and undeclared? What does typeof return for an undeclared variable?
  5. Why can't you add a property to a string primitive? What is autoboxing?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview