World’s largest virtual agentic engineering & quality conference

WHENAUG 19-21
WHEREVirtual · Global
Register Now
DebugJavaScriptMiscellaneous

TypeError: JavaScript

TypeError is thrown when you perform an operation on a value whose type does not support it. This guide covers the common TypeErrors developers hit, how to fix each one, and how to prevent them.

Author

Saif Sadiq

Author

Last Updated on: July 16, 2026

Can you add a number and an alphabet?

Say, if I ask you to give me the result of the addition of 1 and H will you be able to give me the answer?

The obvious answer is NO.

Same goes in JavaScript. When you try to perform an operation on two operands of unmatched type, JavaScript throws a TypeError. In technical terms, a TypeError is thrown when an operand or argument passed to a function is incompatible with the type expected by that operator or function.

TypeError is one of the most frequent runtime errors in JavaScript, alongside a handful of others covered in this guide to common JavaScript errors. This article walks through the specific TypeErrors developers hit most, how to fix each, and how to stop them before they reach production.

Overview

To resolve and prevent JavaScript TypeErrors, use TypeScript for compile-time type safety and run scripts on TestMu AI to catch engine-specific runtime failures. Developers can also fix these errors during runtime by implementing typeof checks, optional chaining, and nullish coalescing to handle unexpected values safely.

  • TypeScript: This tool catches type mismatches during development before your code runs, which eliminates TypeErrors before they reach production.
  • Optional chaining and nullish coalescing: Using ?. and ?? prevents "Cannot read properties of undefined" errors by short-circuiting safe reads and providing fallback values for missing fields.
  • The typeof operator: This operator verifies a value's type before executing a method, preventing "is not a function" errors by ensuring the target is callable.
  • The let keyword: Declaring variables with this keyword instead of const prevents "Assignment to constant variable" TypeErrors when you need to reassign a value.
  • TestMu AI: Running scripts on this automation cloud catches environment-specific TypeErrors that only surface in certain browser engines.

Types of TypeError

For example, you will get an Uncaught TypeError if you try to convert a number to uppercase. toUpperCase() is a string method, so calling it on a number is an incompatible operation. The following code throws an error.

Code structure

var num = 1;
try {
  num.toUpperCase();
}
catch (err) {
  document.getElementById("demo").innerHTML = err.name;
}

Error

Browser console showing an Uncaught TypeError: num.toUpperCase is not a function

The fastest guard is to check the type before calling the method. Use the typeof operator so the string method only runs on an actual string.

var num = 1;
if (typeof num === "string") {
  num.toUpperCase();   // only runs when num is really a string
} else {
  console.log("Not a string, skipping toUpperCase()");
}

How to Fix TypeError: toUpperCase is not a function

If you actually need the uppercase output, convert the number to a string first. There are two common ways to do it.

1. Using toString()

Use toString() to convert the number into a string first, then call toUpperCase() on the result.

var num = 1;
try {
  num.toString().toUpperCase();   // convert the number into a string first
}
catch (err) {
  document.getElementById("demo").innerHTML = err.name;
}

Output

"1"

2. Using new String()

The String() constructor of the predefined String class wraps the number as a string object, so string methods become available.

var num = 1;
num = new String(num);
try {
  num.toUpperCase();   // now valid, num is a String object
}
catch (err) {
  document.getElementById("demo").innerHTML = err.name;
}

Some TypeErrors, like the browser-specific messages older code threw for console.log or prompt, only appear in certain engines. Running your scripts across a real browser matrix surfaces those environment-specific failures before your users do.

Test across 3000+ browser and OS environments with TestMu AI

Common JavaScript TypeError Scenarios (And How to Fix Them)

Beyond the toUpperCase example, three TypeError messages account for most real-world crashes. Here is what each means and the modern way to fix it.

1. Cannot read properties of undefined (or null)

This is the single most common TypeError. It fires when you access a property or method on a value that is undefined or null, usually because an object or array field you expected was not there.

Before

const user = { name: "Ada" };
// user.profile was never set
console.log(user.profile.city);
// Uncaught TypeError: Cannot read properties of undefined (reading 'city')

After - use optional chaining (?.) so the access short-circuits to undefined instead of throwing, and nullish coalescing (??) to supply a fallback value.

const user = { name: "Ada" };

// ?. stops the chain the moment profile is undefined
const city = user?.profile?.city ?? "Unknown";
console.log(city);   // "Unknown"

Note that ?. is what prevents the error by guarding the read; ?? only decides what value to use when the result is null or undefined.

2. x is not a function

This TypeError appears when you call something that is not a function, often a misspelled method, a property that holds a value instead of a function, or a variable reassigned to a non-function.

Before

const list = [1, 2, 3];
// pushh is a typo, it is not a function
list.pushh(4);
// Uncaught TypeError: list.pushh is not a function

After - call the correct method, and when a value might not be callable, verify it with typeof first.

const list = [1, 2, 3];
list.push(4);   // correct method name

// guard a value that may or may not be a function
if (typeof callback === "function") {
  callback();
}

3. Assignment to constant variable

Reassigning a variable declared with const throws a TypeError. A const binding cannot be reassigned after it is created.

Before

const total = 10;
total = 20;
// Uncaught TypeError: Assignment to constant variable.

After - use let when the value needs to change, and keep const for values that never do.

let total = 10;
total = 20;   // valid, let allows reassignment

TypeError vs ReferenceError: What Is the Difference

The two errors are easy to confuse because both often involve undefined, but they point to different root causes. A ReferenceError means the variable was never declared, so the name does not exist in scope. A TypeError means the variable exists but the operation you attempted is not valid for its current type.

// ReferenceError: the name was never declared
console.log(score);
// Uncaught ReferenceError: score is not defined

// TypeError: the variable exists but the operation is invalid for its type
let score = 5;
score.toUpperCase();
// Uncaught TypeError: score.toUpperCase is not a function
AspectReferenceErrorTypeError
CauseAccessing a variable that was never declaredPerforming an operation incompatible with a value's type
Does the name exist?No, the identifier is not in scopeYes, the variable exists but holds the wrong type
Typical messagex is not definedx is not a function, Cannot read properties of undefined
FixDeclare the variable or correct the spellingType-check with typeof or guard with optional chaining

Defensive Coding: How to Prevent TypeErrors in JavaScript

Fixing a TypeError after it crashes is reactive. These practices stop most of them from ever running.

  • Type-check with typeof: Before calling a method or invoking a value, confirm its type. typeof value === "function" and typeof value === "string" catch the two most common TypeError triggers.
  • Use optional chaining and nullish coalescing: Reach into nested objects with ?. and provide safe defaults with ??, so a missing field returns a fallback instead of crashing.
  • Wrap risky operations in try...catch: For code that can fail for reasons outside your control, such as JSON parsing or third-party calls, a try...catch block lets you handle the failure gracefully rather than halting execution.
  • Adopt TypeScript for static safety: TypeScript catches type mismatches at compile time, before the code ever runs, eliminating a whole class of TypeErrors during development. Pair it with unit tests, as covered in this guide to JavaScript unit testing.
  • Reproduce and inspect in the console: When an error does surface, the browser console shows the error name and the exact line. This walkthrough on debugging JavaScript in the browser console shows how to trace it quickly.
Note

Note: TypeErrors often surface only on specific browsers. Test your JavaScript across real browser and OS environments with TestMu AI. Try TestMu AI Today!

Author

...

Saif Sadiq

Blogs: 11

  • Twitter
  • Linkedin

Saif Sadiq is a community contributor with 7+ years of experience working across product, growth, and developer-focused platforms. Currently Director of Product & Growth at Apptile, he leads product strategy and cross-functional execution for no-code mobile app tooling. Saif previously worked at TestMu AI, contributing to product and growth initiatives for a cloud-based cross-browser testing platform, and has been recognized as a most-viewed blogger and writer.

Open in ChatGPT Icon

Open in ChatGPT

Open in Claude Icon

Open in Claude

Open in Perplexity Icon

Open in Perplexity

Open in Grok Icon

Open in Grok

Open in Gemini AI Icon

Open in Gemini AI

Copied to Clipboard!
...

3000+ Browsers. One Platform.

See exactly how your site performs everywhere.

Try it free
...

Write Tests in Plain English with KaneAI

Create, debug, and evolve tests using natural language.

Try for free
...
TestMu Conf 2026

World's largest virtual agentic engineering & quality conference

...

AUG 19-21, 2026

REGISTER NOW

TypeError FAQs

Did you find this page helpful?

More Related Blogs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests