Skip to content
jshacks.dev
Fundamentals

How typeof Works in JavaScript Including the typeof null Bug

The typeof operator returns one of eight strings, reports null as object and arrays as object too. See what it gets right and the checks to use instead.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Vite, npm and TypeScript logos.

typeof is the operator everyone learns in the first week and the one with the most exceptions to what you learned. It names the type of a value, and for six of the seven primitives it does exactly that. The two famous gaps, null and arrays, both report "object", and the third gap, that it is safe on undeclared names and unsafe on some declared ones, tends to surprise people later. This post covers what the operator returns, why null is wrong, and what to use when typeof is not enough. The rest of the type system is in the guide to types and coercion, and the seven primitives are listed in their own post. Examples run on Node.js 24.

The complete table of results is short.

JavaScript
const samples = {
  undefined: undefined,
  boolean: true,
  number: 42,
  bigint: 10n,
  string: "text",
  symbol: Symbol("id"),
  function: () => {},
  object: { id: 1 },
  null: null,
  array: [1, 2],
  date: new Date(0),
  class: class Invoice {},
  NaN: NaN,
};

for (const [label, value] of Object.entries(samples)) {
  console.log(label.padEnd(10), typeof value);
}
Text
undefined  undefined
boolean    boolean
number     number
bigint     bigint
string     string
symbol     symbol
function   function
object     object
null       object
array      object
date       object
class      function
NaN        number

Eight distinct answers appear. Three rows deserve a second look. null reports "object". An array and a date both report "object", because they are objects and typeof does not subdivide them. A class reports "function", because a class is a function underneath, as explained in the post on classes being functions. And NaN reports "number", since it is a numeric value that means "not a valid number", a point covered in the post on NaN.

The null bug

typeof null returning "object" is a defect from the first implementation of the language, kept ever since because fixing it would break code that depends on it. A change to "null" was proposed during the work on ES2015 and abandoned for that reason. The result is a rule you have to memorize: typeof cannot tell you that a value is an object without also checking for null.

JavaScript
function isObject(value) {
  return typeof value === "object" && value !== null;
}

console.log(isObject({}));
console.log(isObject([]));
console.log(isObject(null));
console.log(typeof null === "object");
Text
true
true
false
true

The helper rejects null, and still accepts arrays, dates and anything else shaped like an object. If you need plain objects only, a stricter check looks at the prototype, shown below. The bug matters most in code that reads a property after a typeof check: typeof value === "object" && value.id throws a TypeError on null, because the first half passed.

typeof is safe on undeclared names

Reading an identifier that was never declared throws a ReferenceError. typeof is the exception: it returns "undefined" for a name that does not exist, which makes it the safe way to probe for a global that may or may not be present.

JavaScript
console.log(typeof notDeclaredAnywhere);

try {
  console.log(notDeclaredAnywhere);
} catch (error) {
  console.log(error.name, error.message);
}

console.log(typeof window === "undefined" ? "server" : "browser");
Text
undefined
ReferenceError notDeclaredAnywhere is not defined
server

The last line is the classic use: code that runs on both server and browser tests for window this way. It is less needed now that globalThis exists, as covered in the post on globalThis, since typeof globalThis.window never throws either way.

The safety has one hole. A let, const or class binding that exists but has not been initialized is in its temporal dead zone, and reading it throws even through typeof.

JavaScript
try {
  console.log(typeof later);
  let later = 1;
} catch (error) {
  console.log(error.name, error.message);
}
Text
ReferenceError Cannot access 'later' before initialization

Older advice that typeof never throws predates block scoping. It never throws on a name that does not exist, and it can throw on one that exists but is not ready, which the post on the temporal dead zone explains.

Telling objects apart

Because typeof stops at "object", other tools do the rest. Each answers a narrower question.

JavaScript
const values = [[], new Date(0), new Map(), {}, null, /x/];

for (const value of values) {
  console.log(
    Array.isArray(value),
    Object.prototype.toString.call(value),
  );
}

class Invoice {}
console.log(new Invoice() instanceof Invoice);
console.log(Object.getPrototypeOf({}) === Object.prototype);
Text
true [object Array]
false [object Date]
false [object Map]
false [object Object]
false [object Null]
false [object RegExp]
true
true

Array.isArray() is the correct array test: it works across realms, where instanceof Array does not, a limit described in the post on realms. Object.prototype.toString.call(value) returns a tag string naming the built-in type, which distinguishes dates, maps, regular expressions and null. A prototype check, Object.getPrototypeOf(value) === Object.prototype, identifies a plain object, as opposed to an instance of a class.

We use typeof for primitives and for "is this callable", Array.isArray() for arrays, === null for null and instanceof for classes inside one realm. The tag string is for debugging output and for the few libraries that must classify arbitrary input.

A plain object check you can trust

Most validation code wants "a plain object, not an array, not null, not a class instance". typeof alone cannot say that, and the check that does is worth writing once and testing.

JavaScript
function isPlainObject(value) {
  if (typeof value !== "object" || value === null) return false;
  const proto = Object.getPrototypeOf(value);
  return proto === Object.prototype || proto === null;
}

console.log(isPlainObject({ id: 1 }));
console.log(isPlainObject(Object.create(null)));
console.log(isPlainObject([]));
console.log(isPlainObject(new Date()));
console.log(isPlainObject(null));
Text
true
true
false
false
false

The first line of the function removes every primitive and null in one comparison, and the prototype test removes arrays, dates and class instances, whose prototypes are not Object.prototype. The null prototype case is allowed, because an object made with Object.create(null) is a legitimate dictionary. The check fails for objects that come from another realm, whose Object.prototype is a different object, so a library that must accept those compares the tag string instead.

Writing this once, and importing it, beats the five variations that accumulate in a codebase. Each variation disagrees with the others about arrays or null, and the disagreement surfaces as a bug in whichever module used the loosest one.

Narrowing in TypeScript

typeof is also how TypeScript narrows. Inside a branch guarded by typeof value === "string", the compiler treats value as a string, with no cast.

TypeScript
function describe(value: string | number | null): string {
  if (value === null) return "nothing";
  if (typeof value === "number") return value.toFixed(1);
  return value.toUpperCase();
}

The null check comes first on purpose. In a union that includes null, a typeof value === "object" test would narrow to null and nothing else, which is correct and confusing. Order the checks from the most specific to the most general, and let the compiler's narrowing tell you when you got it wrong.

typeof on the result of typeof

The result is always a string, so typeof typeof x is "string", and comparisons like typeof x === "strnig" fail silently because nothing validates the literal. A typo here is a real class of bug, which TypeScript catches and plain JavaScript does not. Most linters have a valid-typeof rule for it, and we enable it everywhere.

JavaScript
console.log(typeof typeof 1);
console.log(typeof 1 === "numbr");
Text
string
false

Reading old code that uses typeof

Code written before ES2015 leans on typeof heavily, and a few of its idioms are worth recognizing. typeof module !== "undefined" && module.exports detected CommonJS, and typeof define === "function" && define.amd detected an AMD loader, back when a library had to run in all three environments. You will meet these at the top of old bundles. In current code, ES modules and import make the guards unnecessary, and a library that still ships them is carrying weight it no longer needs.

Where typeof is the wrong tool

If you need to know whether a value is a specific class, typeof cannot say. If you need to validate the shape of data from outside, a schema library is the right tool, since a typeof check on each field is a hand-written validator that drifts. If you are checking for undefined on a property, comparing with === undefined is shorter and does not need the operator.

For a value that crosses a realm, a worker or a frame, instanceof lies and tag strings tell the truth, as the post on realms shows.

The operator is defined in the specification under the typeof operator, which lists every result string, and MDN's page for typeof documents the null behavior and the temporal dead zone exception.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.