Skip to content
jshacks.dev
Fundamentals

JavaScript TypeError Explained With Causes and Fixes

JavaScript throws TypeError when a value is not the type an operation needs. See the common causes, exact messages, how to catch it and the fixes for each.

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

TypeError is the error you meet most often in JavaScript, and it is almost always the same story: an operation expected one kind of value and received another. You called something that is not a function, read a property of undefined, assigned to a constant, or iterated over a number. The messages differ and the cause is shared, so the quickest way to fix one is to learn the dozen forms it takes. This post lists them with the exact message Node.js 24 prints, explains what the language was refusing to do, shows the fix for each, and finishes with how to catch the error and how to throw your own. The messages come from the V8 engine, which runs Chrome, Edge and Node.js, so Firefox and Safari word some of them differently, and a program should match on the error type and not on the text.

What the error means

The language throws TypeError when an operation is applied to a value that cannot support it, as the specification defines it. Not every wrong value counts: undefined + 1 is not an error and gives NaN. The error appears when the engine has no sensible coercion to fall back to, such as calling a non-callable value.

JavaScript
const examples = [
  () => null.name,
  () => undefined(),
  () => (123)(),
  () => { const a = 1; a = 2; },
  () => Symbol() + "",
  () => 1n + 1,
  () => new (class A { constructor() { null.x; } })(),
];

for (const run of examples) {
  try {
    run();
  } catch (e) {
    console.log(e.name, "|", e.message);
  }
}
Text
TypeError | Cannot read properties of null (reading 'name')
TypeError | undefined is not a function
TypeError | 123 is not a function
TypeError | Assignment to constant variable.
TypeError | Cannot convert a Symbol value to a string
TypeError | Cannot mix BigInt and other types, use explicit conversions
TypeError | Cannot read properties of null (reading 'x')

Every entry has the same name and a different message. The message names the value and the operation, which is the first clue to read. The sections below take the common ones in order of how often we see them.

Reading a property of null or undefined

This is the most common one, by a wide margin.

JavaScript
const user = { profile: null };

try {
  console.log(user.profile.email);
} catch (e) {
  console.log(e.message);
}

try {
  console.log(user.settings.theme);
} catch (e) {
  console.log(e.message);
}
Text
Cannot read properties of null (reading 'email')
Cannot read properties of undefined (reading 'theme')

The message says which property was being read and on what kind of value. The first object has a profile that is null, and the second has no settings at all. The fix is to decide whether the missing value is possible. If it is, use optional chaining, user.profile?.email, which gives undefined instead of throwing, and supply a default with ??. If it is not possible, the bug is earlier: find where profile should have been set and was not. Writing ?. everywhere to silence the error moves the problem to wherever undefined is used next.

JavaScript
console.log(user.profile?.email);
console.log(user.settings?.theme ?? "light");
Text
undefined
light

Calling something that is not a function

JavaScript
const config = { name: "app", run: "not a function" };

for (const call of [() => config.start(), () => config.run(), () => config.name()]) {
  try {
    call();
  } catch (e) {
    console.log(e.message);
  }
}
Text
config.start is not a function
config.run is not a function
config.name is not a function

The first call names a method that does not exist, and the others a property that holds a string. V8 prints the expression it was evaluating, which is why the message includes config.start. The usual causes are a typo, a method used before it was assigned, a callback parameter that was not passed, and a library function used in the wrong version. Check the value with typeof config.start === "function" before calling when it is optional, or config.start?.() to call only if present.

Assigning to a constant or a read-only property

JavaScript
"use strict";

const limit = 10;

try {
  limit = 20;
} catch (e) {
  console.log(e.message);
}

const frozen = Object.freeze({ a: 1 });

try {
  frozen.a = 2;
} catch (e) {
  console.log(e.message);
}

try {
  delete frozen.a;
} catch (e) {
  console.log(e.message);
}
Text
Assignment to constant variable.
Cannot assign to read only property 'a' of object '#<Object>'
Cannot delete property 'a' of #<Object>

The first is a binding that cannot be reassigned. The other two come from a frozen object in strict mode, which is the mode ES modules and classes always use. In sloppy mode the same assignment to a frozen object does nothing and raises no error, which is why a program can behave differently in a script and in a module. Fix the first with let, or by creating a new value instead of changing the old one. Fix the others by copying the object before changing it: { ...frozen, a: 2 }.

Iterating or spreading a value that is not iterable

JavaScript
const count = 5;
const settings = { theme: "dark" };

for (const input of [() => { for (const x of count) {} }, () => { for (const x of settings) {} }]) {
  try {
    input();
  } catch (e) {
    console.log(e.message);
  }
}

const [a, b] = [1, 2];
console.log(a, b);

try {
  const [first] = null;
} catch (e) {
  console.log(e.name);
}
Text
count is not iterable
settings is not iterable
1 2
TypeError

Numbers and plain objects have no Symbol.iterator, so for...of and spread reject them, as covered in Symbol.iterator. Array destructuring of null fails the same way. Iterate Object.entries(settings) for an object, and check that a function that is supposed to return an array did not return undefined on one code path.

Destructuring null or undefined

JavaScript
function greet({ name }) {
  return `Hello ${name}`;
}

try {
  greet();
} catch (e) {
  console.log(e.message);
}

try {
  const { a } = null;
} catch (e) {
  console.log(e.message);
}

console.log(greet({ name: "Ada" }));
Text
Cannot destructure property 'name' of 'undefined' as it is undefined.
Cannot destructure property 'a' of 'null' as it is null.
Hello Ada

A parameter with a destructuring pattern throws when the call passes nothing. Give the parameter a default, function greet({ name } = {}), or a default for the property, { name = "friend" } = {}, depending on whether an empty call is valid.

Classes and constructors

JavaScript
class Account {
  constructor(owner) {
    this.owner = owner;
  }
}

const arrow = () => {};

try {
  Account("ada");
} catch (e) {
  console.log(e.message);
}

try {
  new arrow();
} catch (e) {
  console.log(e.name);
}

try {
  new Math.max();
} catch (e) {
  console.log(e.name);
}
Text
Class constructor Account cannot be invoked without 'new'
TypeError
TypeError

A class must be called with new, and only some functions can be constructed: arrow functions, methods and most built-in functions cannot. The fix is almost always to add new, or to stop using new on something that is a plain function.

Mixing types the language will not coerce

JavaScript
const pairs = [
  () => 1n + 1,
  () => Symbol("x") + "",
  () => JSON.stringify(1n),
  () => { const o = {}; o.self = o; return JSON.stringify(o); },
];

for (const run of pairs) {
  try {
    run();
  } catch (e) {
    console.log(e.message.split("\n")[0]);
  }
}
Text
Cannot mix BigInt and other types, use explicit conversions
Cannot convert a Symbol value to a string
Do not know how to serialize a BigInt
Converting circular structure to JSON

Each is a conversion the language refuses. Convert explicitly: BigInt(1) + 1n or Number(big) + 1, String(symbol) or symbol.description, a replacer function for BigInt in JSON.stringify, and a structure without cycles, or a library that handles them, for the last one. The multi-line message for the circular case lists the path of the cycle, and we split on the newline here only to keep the output short.

Catching it

JavaScript
function parse(json) {
  try {
    return JSON.parse(json);
  } catch (e) {
    if (e instanceof SyntaxError) return null;
    throw e;
  }
}

console.log(parse("{bad"));

try {
  null.x;
} catch (e) {
  console.log(e instanceof TypeError, e instanceof Error, e.name, e.constructor === TypeError);
}
Text
null
true true TypeError true

Catch by type with instanceof, and rethrow what you do not handle, as parse() does for anything that is not a SyntaxError. A bare catch that swallows every error would also swallow a TypeError from a bug. Catching a TypeError to recover is rarely right: the error usually means the code is wrong, and the correct response is to fix the code, not to retry.

Throwing your own

Validate inputs at the edge of a function and throw a TypeError with a message that names the parameter.

JavaScript
function repeat(text, times) {
  if (typeof text !== "string") {
    throw new TypeError(`repeat: text must be a string, got ${typeof text}`);
  }
  if (!Number.isInteger(times)) {
    throw new TypeError(`repeat: times must be an integer, got ${times}`, {
      cause: { times },
    });
  }
  return text.repeat(times);
}

try {
  repeat("ab", 2.5);
} catch (e) {
  console.log(e.message);
  console.log(e.cause);
}
Text
repeat: times must be an integer, got 2.5
{ times: 2.5 }

The second argument carries a cause, which keeps structured details for whoever catches it. Use TypeError for a wrong type, and RangeError for a value of the right type outside its allowed range, such as a negative length.

A mistake we hit: swallowing the error with a default

JavaScript
function getName(user) {
  try {
    return user.profile.name;
  } catch {
    return "Anonymous";
  }
}

console.log(getName({ profile: { name: "Ada" } }));
console.log(getName({}));
console.log(getName(null));
console.log(getName({ profile: { nam: "typo" } }));
Text
Ada
Anonymous
Anonymous
undefined

The function hid two real problems behind a default. The null user was a bug upstream, and the object with the misspelled key returned undefined instead of the default, because reading a missing property is not an error. We replaced the try with explicit checks, user?.profile?.name ?? "Anonymous", which makes the intent visible and lets a true bug throw.

Choosing between the fixes

The message saysThe usual fix
Cannot read properties of undefinedOptional chaining, or fix the missing assignment
x is not a functionCheck the name and the type before calling
Assignment to constant variableUse let, or build a new value
x is not iterableUse Object.entries(), or return an array on every path
Cannot destructure propertyAdd a default to the parameter
Class constructor cannot be invoked without 'new'Add new
Cannot mix BigInt and other typesConvert explicitly

Practical rules we follow

Read the message before the stack: it names the value and the operation. Validate at boundaries and trust values inside. Use optional chaining for values that may be missing and nothing else. Throw TypeError for wrong types in your own code, with the name of the parameter in the message. Match on the error class, never on the message text, since engines word them differently. And let programming errors reach the top level, where a logger can record them with a stack trace.

Where TypeError stops being the right diagnosis

It tells you what was refused and not why the value was wrong. The cause is usually earlier in the program, in code that returned undefined or loaded data that was not there. It is one of several built-in errors: a syntax mistake is a SyntaxError, a missing variable is a ReferenceError, and a value out of range is a RangeError. The reference is in the MDN TypeError page and the ECMAScript specification.

Taggederrors
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.