Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

TypeError

A wrong type error — for example, calling a method on undefined.

Available since: ES3

Syntax

new TypeError(message)

Parameters

ParameterTypeDescription
messagestringOptional. A description of the error.

Return value

TypeErrorAn error object.

Examples

The most common error — reading a property of undefined:

const user = undefined;
 
try {
  console.log(user.name);
} catch (error) {
  console.log(error.name);
}

Output:

TypeError

A custom TypeError for argument checks:

function double(n) {
  if (typeof n !== 'number') {
    throw new TypeError(`Expected a number, got ${typeof n}`);
  }
  return n * 2;
}
 
try {
  double('5');
} catch (error) {
  console.log(String(error));
}

Output:

TypeError: Expected a number, got string

Notes

Most TypeErrors come from undefined or null where an object was expected. The ?. operator helps: user?.name.

See also

  • Error — The base error class: created and thrown with throw.
  • ReferenceError — A variable does not exist error.
  • Optional chaining (?.) — Safe property access: returns undefined instead of an error if the object is missing.

In the tutorial

  • Errors and try...catch — Error handling in JavaScript: try, catch and finally blocks, the error object, the throw statement and built-in error types.

Thanks for reading!

Donate to the site — we work hard for you.