Reading Error Messages — Debugging

An error in the Console has four parts: the type (TypeError, ReferenceError, SyntaxError, RangeError), the message (the reason), the location…

Red text appears in the Console. The first thing most people do: copy all of it, then paste it into Google. But that red text is a report, and it usually tells you almost everything you need.

An error message is the browser's report when code stops because of a problem. It names four things: the type of problem, the reason, where it happened, and the path of function calls that led there. It looks like a failed-delivery note from a courier: "Delivery failed (type), address not found (reason), 12 Jasmine Street (location), route main warehouse, city transit hub, local courier (path)". If you can read all four, you find most bugs without guessing.

Anatomy of one error

Here is app.js, a small file. The "See profile" button on the page should show a user's name in capitals.

const response = '[{"id":1,"name":"Budi"}]';
const users = JSON.parse(response);

function findUser(id) {
  return users.find((u) => u.id === id);
}

function showName(user) {
  return user.name.toUpperCase();
}

function showProfile(id) {
  const user = findUser(id);
  return showName(user);
}

const button = document.querySelector("#view");
button.addEventListener("click", () => {
  console.log(showProfile(2));
});

When the button is clicked, Chrome's Console shows this in red:

Uncaught TypeError: Cannot read properties of undefined (reading 'name')
    at showName (app.js:9:15)
    at showProfile (app.js:14:10)
    at HTMLButtonElement.<anonymous> (app.js:19:15)

Stack trace: read from the top

The at ... lines are the path of calls. They are called the stack trace: the list of functions that were running when the error happened. The function called last is at the top, the same as the Call Stack in the Sources panel.

Line What it means
at showName (app.js:9:15) this is where the code stopped
at showProfile (app.js:14:10) the function that called showName, on line 14
at HTMLButtonElement.<anonymous> (app.js:19:15) where it all started: a function with no name, running as the button's click listener

Click app.js:9:15 in the Console, and the Sources panel opens right on that line. A stack trace can be long and full of lines from libraries (ready-made code written by other people, for example react-dom). In that case, look for the first line that points at your file.

But the code doesn't always stop where the cause is. user is undefined because findUser(2) found no user with id 2. The users data only holds a user with id 1, and when nothing matches, find returns undefined. findUser had already finished running before the error happened, so its name isn't in the stack trace, which lists only the functions still running. This means the cause of an error can be in a function that isn't listed in the stack trace at all. The stack trace tells you where the code stopped, but you still have to ask where the wrong value came from.

The four most common error types

Type Example message (exactly as Chrome prints it) What it means, check this first
TypeError Cannot read properties of undefined (reading 'name') the value before .name is undefined: the data hasn't arrived, or a search found nothing
TypeError users.findd is not a function what was called isn't a function: a typo in a method name, or the value isn't the type you thought
TypeError Cannot set properties of null (setting 'textContent') querySelector didn't find the element, so it returned null
ReferenceError usr is not defined the line can't find a variable with that name in its scope: a typo, or the variable was created in another function
ReferenceError Cannot access 'total' before initialization a let/const variable was used before the line that creates it ran
SyntaxError Unexpected token '<', "<!DOCTYPE "... is not valid JSON JSON.parse got an HTML page, not JSON. Usually a 404 page from a wrong API URL
SyntaxError Unexpected end of input a curly brace or another bracket was never closed
RangeError Maximum call stack size exceeded a recursive function (a function that calls itself) that never stops

There are two kinds of SyntaxError. A SyntaxError from badly written code appears when the file loads, before a single line runs. A SyntaxError from JSON.parse appears when that JSON.parse line runs. Its stack trace starts with at JSON.parse (<anonymous>), which is a function built into the browser. The line below it points at your code.

The messages in that table are exactly Chrome's. Node.js (a program that runs JavaScript outside the browser) uses the same messages, because it uses the same JavaScript engine as Chrome. Firefox writes the same errors with other words. So remember the error type and the names the message mentions, not the exact sentence:

Chrome Firefox
Cannot read properties of undefined (reading 'name') can't access property "name", user is undefined
Cannot set properties of null (setting 'textContent') can't access property "textContent", document.querySelector(...) is null
Unexpected token '<', "<!DOCTYPE "... is not valid JSON JSON.parse: unexpected character at line 1 column 1 of the JSON data
RangeError: Maximum call stack size exceeded InternalError: too much recursion

A Firefox stack trace looks different too. Each line is written functionName@file-address:line:column, with no at, and the column number can differ from Chrome's. One advantage of Firefox: its message names the value that is undefined directly, as in user is undefined.

An error that isn't caught in top-level code (code outside any function) stops the rest of the script. For example, in the app.js at the start of this lesson: if JSON.parse on line 2 fails, lines 17 to 20 never run. The click listener is never added, so the button does nothing when clicked.

Errors in async code

When an error inside an async function isn't caught, Chrome prints it with the prefix Uncaught (in promise):

Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

To catch it, put the await inside a try/catch, and check response.ok before reading the JSON:

async function loadUsers() {
  try {
    const response = await fetch("/api/users");
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return await response.json();
  } catch (error) {
    console.error("Failed to load users:", error.message);
    return [];
  }
}

Exercise: sorting errors and throwing your own

The exercise has two functions. classifyError(errorMessage) guesses an error's type from pieces of text in its message. The pieces are checked in order, and the function returns as soon as one matches. safeDivide(a, b) divides a by b, but first it refuses input that makes no sense, with throw. Here is the finished safeDivide:

function safeDivide(a, b) {
  if (typeof a !== "number" || typeof b !== "number") throw new Error("Not a number");
  if (b === 0) throw new Error("Division by zero");
  return a / b;
}

The exercise's starting code calls safeDivide inside a try/catch, and prints e.message when there is an error. This is what each call prints:

Call What gets printed
classifyError("x is not defined") ReferenceError
classifyError("foo is not a function") TypeError:NotFunction
classifyError("Cannot read properties of null") TypeError:NullAccess
classifyError("Unexpected token }") SyntaxError
classifyError("Something went wrong") Unknown
safeDivide(10, 2) 5
safeDivide(10, 0) Division by zero (from e.message in the catch)
safeDivide("abc", 2) Not a number

Why the guards (the two if lines at the start of safeDivide)? Without them, 10 / 0 in JavaScript is no error, but it gives Infinity. "abc" / 2 is no error either, it gives NaN (not a number). Those two values go quietly into the next calculations. throw stops the code right there, with a message that explains why.

🎯 Stack traces in production

In production (the version of the code that visitors use), code is usually minified: function names are shortened, and all the code becomes one long line. The stack trace then looks like this:

Uncaught TypeError: Cannot read properties of undefined (reading 'name')
    at q (app.min.js:1:48291)
    at r (app.min.js:1:49012)

q on line 1 column 48,291 can't be read by a human: you don't know which function q is. The fix is a source map, a .map file that maps that position back to the original file and line. DevTools reads a source map automatically when the file is available. The Source Maps lesson in this track covers it fully.

⚠️ Ways of reading an error that send you the wrong way

TL;DR: An error in the Console has four parts: the type (TypeError, ReferenceError, SyntaxError, RangeError), the message (the reason), the location file:line:column, and the stack trace (the list of functions that were running when the error happened). The stack trace is read from the top. The first line is where the code stopped, and below it are the functions that called it. At the bottom is where it started, for example a click listener (the function that runs when a button is clicked). Cannot read properties of undefined (reading 'name') means the value before .name is undefined. x is not a function means what was called isn't a function. x is not defined means that name isn't in scope (the variables that line can use). Unexpected token '<' from JSON.parse means the server sent HTML, not JSON. The cause of an error can be in a function that already finished running, and that function isn't listed in the stack trace. An uncaught error in async code starts with Uncaught (in promise). Catch it with try/catch around the await, and throw your own error with throw new Error("message").

⚡ Four parts of one error

Write:

Uncaught TypeError: Cannot read properties of undefined (reading 'name')
    at showName (app.js:9:15)
    at showProfile (app.js:14:10)
    at HTMLButtonElement.<anonymous> (app.js:19:15)

Meaning: This is one error in Chrome's Console, with four parts. The type is TypeError, and the message is Cannot read properties of undefined (reading 'name'). The location is app.js:9:15 (file, line 9, column 15). The at lines are the stack trace: the list of functions that were running when the error happened.

⚡ What's undefined is the value in front

Guess first: the code is user.name.toUpperCase(), and the message says (reading 'name'). What is undefined?

Not name, but the value before .name, which is user. Usually the data hasn't arrived yet, or the code that looks for the user found nothing.

Meaning: Cannot read properties of undefined always points at the value in front of the dot, not at the property name in the brackets.

⚡ Read the stack trace from the top

Meaning: In a stack trace, the first line is where the code stopped, and below it are the functions that called it. At the bottom is where it started (in this example, the button's click listener). But the cause can be in a function that already finished running. In this example, user is undefined because findUser(2), the function that looks for the user with id 2, didn't find that user. findUser had finished before the error happened, so its name isn't listed in the stack trace.

⚡ Throw your own error

Write:

function safeDivide(a, b) {
  if (typeof a !== "number" || typeof b !== "number") throw new Error("Not a number");
  if (b === 0) throw new Error("Division by zero");
  return a / b;
}
Guess first: without those two if lines (the guards), what does 10 / 0 give in JavaScript?

No error, it gives Infinity. "abc" / 2 is no error either, it gives NaN (not a number). Those two values go quietly into the next calculations.

Meaning: throw throws an error of your own: the code stops right there, with a message that explains why.

What you will learn