10 Common JavaScript Errors and How to Fix Them
Common JavaScript errors can stop a project cold, whether you’re building your first to-do app or maintaining a production dashboard. The good news is that most of them fall into a few predictable groups. You’ll see a ReferenceError when a variable doesn’t exist, a TypeError when a value isn’t what your code expected, a SyntaxError when the engine can’t parse your code, and a handful of async problems tied to promises.
Once you can read an error message and know what it’s telling you, debugging gets faster. This guide covers the ten errors developers run into most often. For each one you get the exact message you’re likely to see, the usual cause, broken and fixed code, and a habit that keeps it from coming back.
Table of Contents
Quick Reference: Common JavaScript Errors at a Glance
If you’re in the middle of debugging, start with this table and then jump to the section that matches your message.
| # | Error message (Chrome wording) | Error type | Most likely cause |
|---|---|---|---|
| 1 | x is not defined | ReferenceError | Typo, missing import, or out-of-scope variable |
| 2 | Cannot access 'x' before initialization | ReferenceError | Using a let/const variable before its declaration |
| 3 | Cannot read properties of undefined (reading 'x') | TypeError | Accessing a property on missing data |
| 4 | x is not a function | TypeError | Calling something that isn’t a function |
| 5 | Assignment to constant variable | TypeError | Reassigning a const |
| 6 | Unexpected token / missing ) after argument list | SyntaxError | Unbalanced brackets, quotes, or commas |
| 7 | Unexpected token '<' ... is not valid JSON | SyntaxError | Parsing HTML or empty text as JSON |
| 8 | Maximum call stack size exceeded | RangeError | Infinite recursion |
| 9 | Uncaught (in promise) | Any (rejected promise) | A rejected promise with no handler |
| 10 | Promise {<pending>} / [object Promise] | Logic bug | Forgetting await |
Wording differs a little between browsers. Firefox, for example, reports error #3 as x is undefined. The error type stays the same everywhere, though, and that’s the part to focus on.
How to Read a JavaScript Error Message
Every uncaught error in the browser console has three parts you should check:
- The error type (
TypeError,ReferenceError, and so on) tells you which category of problem you have. - The message describes what went wrong, often naming the variable or property involved.
- The stack trace lists the file and line number, plus the chain of function calls that led there.
Click the file link next to the message in Chrome or Firefox DevTools. It jumps straight to the failing line, which is usually faster than searching your code by hand.
ReferenceError: Variable and Scope Problems
A ReferenceError means JavaScript tried to look up a name and couldn’t use it.
1. ReferenceError: x is not defined
This is probably the most frequent error beginners see. The engine searched every scope it can reach and found no variable with that name.
javascript
function greet() {
const userName = "Ava";
}
greet();
console.log(userName); // ReferenceError: userName is not defined
userName exists only inside greet(). Outside that function, it’s out of scope.
How to fix it:
javascript
function greet() {
const userName = "Ava";
return userName;
}
const userName = greet();
console.log(userName); // "Ava"
Other common causes:
- A typo or casing mismatch (
usernamevs.userName). JavaScript is case-sensitive. - A library that hasn’t loaded yet, such as a
<script>tag that comes after the code that uses it. - A missing
importstatement in an ES module.
2. ReferenceError: Cannot access ‘x’ before initialization
Variables declared with let and const are hoisted, but they can’t be used until the line that declares them has run. The stretch between the start of the scope and the declaration is called the temporal dead zone (TDZ).
javascript
console.log(total); // ReferenceError
let total = 100;
How to fix it: Declare and initialize the variable before you use it.
javascript
let total = 100;
console.log(total); // 100
The same thing happens with class declarations and with circular imports between modules. If the error shows up in a module, check whether two files import each other.
TypeError: When Values Aren’t What You Expected
A TypeError means the variable exists, but its value doesn’t support the operation you’re trying to perform.
3. TypeError: Cannot read properties of undefined
You’ll see this one constantly when you work with API data, DOM elements, or nested objects. You tried to read a property from something that is undefined or null.
javascript
const user = { name: "Ava" };
console.log(user.address.city);
// TypeError: Cannot read properties of undefined (reading 'city')
user.address is undefined, so asking for .city on it fails.
How to fix it: Use optional chaining (?.) with a fallback, or check for the value explicitly.
javascript
// Option 1: optional chaining + nullish coalescing
const city = user.address?.city ?? "Unknown";
// Option 2: explicit check
if (user.address) {
console.log(user.address.city);
}
In DOM code the cause is usually a selector that didn’t match anything, or a script that ran before the HTML loaded:
javascript
const button = document.querySelector("#submit-btn");
button.addEventListener("click", handleClick); // fails if button is null
Check the selector, and load the script with defer (or place it at the end of <body>) so the element exists before your code looks for it.
4. TypeError: x is not a function
You called something with parentheses, but it isn’t a function.
javascript
const scores = { math: 90, science: 85 };
scores.map((s) => s * 2); // TypeError: scores.map is not a function
.map() is an array method, and scores is a plain object.
How to fix it: Convert the value to the type you need, or call a method that actually exists on it.
javascript
const doubled = Object.values(scores).map((s) => s * 2);
console.log(doubled); // [180, 170]
Other common causes:
- Misspelled method names, such as
document.getElementByIDinstead ofgetElementById. - A variable that shadows a function name.
- A default vs. named import mismatch (
import fetchData fromwhen the module exports{ fetchData }).
5. TypeError: Assignment to constant variable
const blocks reassignment of the binding. It does not make the value itself immutable.
javascript
const count = 0;
count = count + 1; // TypeError: Assignment to constant variable.
How to fix it: Use let when a value needs to change.
javascript
let count = 0;
count = count + 1; // 1
Keep in mind that changing the contents of a const object or array is allowed:
javascript
const cart = [];
cart.push("laptop"); // works fine
A good default is const everywhere, switching to let only when you really need to reassign. That rule catches accidental reassignments early.
SyntaxError: When JavaScript Can’t Parse Your Code
A SyntaxError stops the whole script before it runs. That’s why a page can go completely blank because of one missing character.
6. SyntaxError: Unexpected token or missing ) after argument list
These messages mean the parser ran into something that doesn’t belong where it found it. Typical causes are unbalanced brackets, unclosed strings, and missing commas.
javascript
const product = {
name: "Keyboard"
price: 49.99 // SyntaxError: Unexpected identifier 'price'
};
console.log("Total: " + product.price; // SyntaxError: missing ) after argument list
How to fix it:
javascript
const product = {
name: "Keyboard",
price: 49.99,
};
console.log("Total: " + product.price);
The reported line number is often after the real mistake, because the parser only notices something is wrong once it reaches the next token. Look at the line above as well. A code editor with syntax highlighting and a formatter like Prettier will catch most of these as you type.
7. SyntaxError: Unexpected token ‘<’ … is not valid JSON
This one confuses many developers because the JavaScript itself is fine. The problem is the data you’re parsing.
javascript
const response = await fetch("/api/users");
const data = await response.json();
// SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
The < is the first character of an HTML page. The server returned an HTML 404 page, an error page, or a login page instead of JSON, and .json() tried to parse it anyway.
How to fix it: Check the response before you parse it.
javascript
async function getUsers() {
const response = await fetch("/api/users");
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}
Also confirm the URL is correct and look at the response body in the Network tab of DevTools. The same error shows up when you call JSON.parse() on an empty string or on undefined, so wrap risky parsing in try...catch.
RangeError: Maximum Call Stack Size Exceeded
8. RangeError: Maximum call stack size exceeded
Each function call adds a frame to the call stack. If a function keeps calling itself and never stops, the stack fills up and the engine throws this error.
javascript
function countdown(n) {
console.log(n);
countdown(n - 1); // no stopping condition
}
countdown(5); // RangeError: Maximum call stack size exceeded
How to fix it: Every recursive function needs a base case.
javascript
function countdown(n) {
if (n < 0) return; // base case
console.log(n);
countdown(n - 1);
}
A less obvious version comes from getters or setters that call themselves:
javascript
class User {
set name(value) {
this.name = value; // calls the setter again, forever
}
}
Store the value in a separate field such as this._name or a private field like this.#name.
Promise Errors and Async Mistakes
Async code produces some of the hardest errors to track down, because the failure often shows up far from where it started.
9. Uncaught (in promise): Unhandled Promise Rejections
When a promise rejects and nothing handles the rejection, the browser logs Uncaught (in promise) followed by the original error. In Node.js, unhandled rejections crash the process by default since Node 15.
javascript
fetch("https://invalid-domain.example/data")
.then((res) => res.json())
.then((data) => console.log(data));
// Uncaught (in promise) TypeError: Failed to fetch
How to fix it: Handle rejections with .catch(), or with try...catch inside an async function.
javascript
// With .then() chains
fetch("/api/data")
.then((res) => res.json())
.then((data) => console.log(data))
.catch((error) => console.error("Could not load data:", error));
// With async/await
async function loadData() {
try {
const res = await fetch("/api/data");
const data = await res.json();
console.log(data);
} catch (error) {
console.error("Could not load data:", error);
}
}
Note that fetch() only rejects on network failures. A 404 or 500 response still resolves, so you need the response.ok check from error #7 as well.
10. Forgetting await: Promise {<pending>} and [object Promise]
This bug doesn’t always throw an error, which is exactly why it’s hard to find. You end up with a promise object where you expected real data.
javascript
async function getUser() {
const res = await fetch("/api/user");
return res.json();
}
const user = getUser();
console.log(user.name); // undefined: user is a Promise
document.title = `Hi, ${user}`; // "Hi, [object Promise]"
How to fix it: await the result inside an async function (or a module with top-level await), or use .then().
javascript
const user = await getUser();
console.log(user.name);
A related trap is using forEach with async callbacks. forEach doesn’t wait for promises, so code after it runs too early:
javascript
// Problem: "Done" logs before any save finishes
items.forEach(async (item) => {
await saveItem(item);
});
console.log("Done");
// Fix: run in parallel and wait for all of them
await Promise.all(items.map((item) => saveItem(item)));
console.log("Done");
If the items have to be saved in order, use a for...of loop with await inside it.
Best Practices to Prevent Common JavaScript Errors
Fixing errors one by one works, but a few habits stop most of them before they happen:
- Use a linter. ESLint flags undefined variables, unreachable code, and floating promises before you run anything.
- Use a formatter. Prettier rewrites your code into a consistent layout, which makes missing brackets and commas easy to spot.
- Consider TypeScript. Static typing catches many
TypeErrorproblems, such as calling a method on a value that might beundefined, at compile time. - Validate external data. Treat API responses, user input, and
localStoragevalues as untrusted until you’ve checked their shape. - Handle every promise. Every async call should have a
catchpath somewhere, even if it only logs the error. - Read the full stack trace. The top line shows where the error was thrown, but the cause is often a few frames further down.
Frequently Asked Questions
What is the most common JavaScript error?
For most developers it’s the TypeError “Cannot read properties of undefined.” It comes up whenever code assumes data exists before it has actually loaded, which is very common with APIs and DOM elements.
What’s the difference between a ReferenceError and a TypeError?
A ReferenceError means the variable itself can’t be used, because it was never declared or is in its temporal dead zone. A TypeError means the variable exists but holds the wrong kind of value for the operation, like calling a number as a function.
Why does one SyntaxError break my entire script?
The engine has to parse the whole script before running any of it. If parsing fails, nothing in that file executes. Other scripts on the page still run unless they depend on the broken one.
Should I wrap all my code in try…catch?
No. Use try...catch around operations that can realistically fail, such as network requests, JSON.parse(), and third-party APIs. Wrapping everything hides real bugs and makes debugging harder.
How do I find which line caused an error?
Open DevTools (F12 in most browsers), go to the Console tab, and click the file link next to the error. In Node.js, the stack trace printed in the terminal includes file paths and line numbers.
Conclusion
Most common JavaScript errors come down to a handful of root causes. Variables are used out of scope or before they’re declared, values are missing or the wrong type, the syntax is broken, or async code isn’t awaited and handled. Once you can recognize the error type and read the stack trace, most of these take minutes to fix.
A good next step is to set up ESLint and Prettier in your current project, then add proper .catch() or try...catch handling to every network request. Those two changes alone prevent a large share of the bugs covered here. For more hands-on practice, check out the related programming guides on OnexBayte, including our list of JavaScript projects for beginners.