Loading

T0 Learning to learn · Lesson 2

Reading error messages, in the terminal and in the browser

Every part of an error report: Node's file, line, column and caret, the SyntaxError family, the messages from a running program, the browser's console and other engines' wording, and how to search for a message.

  • run a JavaScript file with Node in a terminal, and read every line of its error report
  • find the exact place of a slip from file:line:column and the caret
  • say what each common SyntaxError message means, and where to look
  • read Cannot read properties of undefined, is not a function and RangeError, and fix each
  • use the browser's console, and read other engines' wording of a message
  • search for an error message so that the answers are about your problem
About 60 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-10-26)Play this lesson's games

The back cover

When a program goes wrong, the computer does not stay silent. It writes a short report: where the trouble is, what kind of trouble it is, and a few words about it. Many beginners see the red text and look away. Yet the report is the most useful thing on the screen.

These pages take such reports apart, piece by piece. A file is run in a terminal, and Node answers with a place, a small arrow under the exact spot, and a message. One family of messages comes before a program starts, when its lines cannot even be read. Another family comes while it runs, when a value is not what a line needed. The browser keeps the same kind of report in a hidden panel, the console.

The last part is about a message that still makes no sense: how to search for it so that the answer is found, where the good answers live, and how to ask a question that other people can answer.

Before you start

The story: Red marks in Inkwell Lane

A lamp in Inkwell Lane has stopped showing the time. Instead, its window shows a line of red marks, a word you do not know, and a number. A small crowd stands under it.

Corin pushes through with a hammer. "It is broken. I will open it up." Ilse catches his wrist without looking. "It is not broken," she says. "It is talking. It is telling you what went wrong, and where. Read it before you hit it."

Everyone turns to you. The red line glows in the fog. You read it once, and it means nothing at all.

Lesson 1 met three error messages and a way to read them. This lesson reads every part of an error report, in the page, in a terminal and in a browser, and meets most of the messages a beginner will ever see. Here is what it builds on. Each line has a tiny example; if one feels shaky, go back to lesson 1 for a few minutes first.

What you already knowA tiny exampleWhere it comes back
The three kinds of error.SyntaxError: the code cannot be read. ReferenceError: a name is unknown. TypeError: a value is used the wrong way.Every report in this lesson starts with its kind.
A message has a kind and a detail.ReferenceError: price is not defined. The kind is before the colon, the detail after it.We read the detail word by word.
The trace names a line.at line 2 means the second line of the code block, counting from 1.Node and the browser name lines too, and columns as well.
Lines run from the top down.Lines before an error run; lines after it do not.Output printed before an error tells you how far the program got.
Strings and numbers."40" is text; 40 is a number; typeof tells them apart.Some messages appear only when a value has the wrong type.
const and let.const never changes; let can be changed later.A let made without a value is the start of the most common error of all.
Folders hold files.A cupboard holds shelves, a shelf holds boxes. A folder called shop can hold a file called bill.js.Node's report starts with the file's full address.
A row and a seat.A cinema ticket says row 4, seat 26: the row first, then the place along it.A line and a column: line 4, column 26.
Counting characters.In the word chai, c is the 1st character and i the 4th.Columns are counted in characters, starting at 1.
Typing a command.You type a message and press Send; nothing happens before Send.In a terminal you type a command and press Enter.

By the end of this lesson you will be able to:

  • run a JavaScript file with Node in a terminal, and read every line of the error report it prints;
  • find the exact place of a slip from a file, line and column, and from the caret under the line;
  • say what each common SyntaxError message means, and where to look for its slip;
  • read the runtime messages Cannot read properties of undefined, is not a function and RangeError, and fix the slip behind each;
  • open the browser's console, read an error there, and know why another browser words it differently;
  • search for an error message so that the answers you find are about your problem.

In one line

This lesson reads an error report line by line, wherever it appears: you need only lesson 1, folders and files, and counting along a line.

Running a file in a terminal, and reading Node's report

At a glance

A terminal is a window where commands are typed to the computer, one line at a time. It is also called the command line or the shell. The command node, followed by the name of a file, runs the JavaScript in that file. Real programs live in files and are run this way, with no web page around them.

When a file has a slip, Node prints a report in place of the output. Three parts of it are worth reading first. The place gives the file's name and the line number. The caret, a small arrow like ^, sits under the exact spot. The last part names the kind of error and adds a message in words. The lines that start with node:internal belong to Node itself and can be skipped.

Take a guess: In Node's report, which comes first: the place of the error, or the words that describe it?

The code blocks on these pages are like the nets at a cricket ground: a safe place to practise. Real programs live in files and run on a real computer, like a real match. The tool for that is the terminal.

Terminal

A window where you type commands to the computer, one line at a time, and press Enter to run each one. It is also called the command line or the shell.

A terminal shows a prompt at the start of the line where you type. In this school the prompt is written as the folder you are in followed by a dollar sign, such as /home/asha/shop$. You never type the prompt itself; you type what comes after it.

To run a JavaScript file, type node, a space, and the file's name. Node reads the file from the top, runs it, and prints what it prints. Here is a file called hello.js, then the terminal after running it.

hello.js

console.log("Namaste from Node");
console.log("Total:", 40 + 55);

Terminal

/home/asha/shop$ node hello.js
Namaste from Node
Total: 95

The output is the same as it would be on this page. The difference shows when something goes wrong, because Node prints a much fuller report than the page does.

Trying this on your laptop

Open a terminal (on Windows, the app called Terminal; on a Mac, Terminal in Utilities; on Linux, Terminal). Type node --version and press Enter. If it prints a version such as v22.23.1, Node is installed. If it says the command is not found, install Node from nodejs.org first (the Node.js step shows how). Then make a folder, save the file in it with any code editor, and type node hello.js in that folder.

A report, line by line

Here is a small bill program with a slip on its last line. Read the file first, then the report.

bill.js

const price = 40;
const qty = 3;
console.log("Bill:", price * qty);
console.log("With tax:", bill * 1.05);

Terminal

/home/asha/shop$ node bill.js
Bill: 120
/home/asha/shop/bill.js:4
console.log("With tax:", bill * 1.05);
                         ^

ReferenceError: bill is not defined
    at Object.<anonymous> (/home/asha/shop/bill.js:4:26)
    at Module._compile (node:internal/modules/cjs/loader:1781:14)
    at Object..js (node:internal/modules/cjs/loader:1913:10)
    at Module.load (node:internal/modules/cjs/loader:1505:32)
    at Function._load (node:internal/modules/cjs/loader:1309:12)
    at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
    at node:internal/main/run_main_module:36:49

Node.js v22.23.1

It looks like a wall of text. It is not. It has six parts, and you need only three of them most of the time.

PartHereWhat it tells you
1. Output before the errorBill: 120the program ran up to line 3 without trouble
2. Where: the file and the line/home/asha/shop/bill.js:4the file, then a colon, then the line number: line 4 of bill.js
3. The line itself, with a caret under itthe line of code, then a ^ under billthe exact spot on that line where the computer stopped
4. The kind and messageReferenceError: bill is not definedwhat went wrong, as in lesson 1
5. The stack: lines starting with atthe first at line names bill.js:4:26; the rest name node:internalthe first one is yours: file, line 4, column 26. The node:internal ones are Node's own machinery: skip them.
6. The versionNode.js v22.23.1which Node ran it; give this when you ask someone for help

The caret is the small ^ sign. It sits under the exact character where the problem was found, like a finger pointing at a word in a book. Here it points at bill.

The numbers 4:26 are the line and the column: line 4, character 26 along that line, counting from 1. Count it once to believe it: console.log( is 12 characters, "With tax:" is 11 more, which makes 23, the comma is the 24th and the space the 25th. So the b of bill is the 26th character. Code editors show the line and column of the cursor at the bottom of the window, so you never have to count by hand.

Now the fix. The message says bill is not defined. Compare with the names that were made: price and qty. Nobody made bill. The writer meant the bill from line 3, but that was printed, never kept in a name. The fix is to keep it in a name first.

bill.js

const price = 40;
const qty = 3;
const bill = price * qty;
console.log("Bill:", bill);
console.log("With tax:", bill * 1.05);

Terminal

/home/asha/shop$ node bill.js
Bill: 120
With tax: 126

The three parts to read first

Where (the first line: file and line), the caret (the exact spot), and the kind and message. Read the rest only when those three are not enough.

Worked example 1

Read this report and say which line has the slip, which word the caret points at, and what the slip is.

What we have: a file name.js and Node's report for it

What we need: the line, the word, and the slip

The plan: read the three key parts: where, the caret, the kind and message

name.js

let customer;
console.log("Customer:", customer);
console.log("Letters:", customer.length);

Terminal

/home/asha/shop$ node name.js
Customer: undefined
/home/asha/shop/name.js:3
console.log("Letters:", customer.length);
                                 ^

TypeError: Cannot read properties of undefined (reading 'length')
    at Object.<anonymous> (/home/asha/shop/name.js:3:34)
    at Module._compile (node:internal/modules/cjs/loader:1781:14)
    at Object..js (node:internal/modules/cjs/loader:1913:10)
    at Module.load (node:internal/modules/cjs/loader:1505:32)
    at Function._load (node:internal/modules/cjs/loader:1309:12)
    at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
    at node:internal/main/run_main_module:36:49

Node.js v22.23.1
  1. Where: name.js:3, so line 3.
  2. The caret is under the dot before length, at column 34.
  3. The message: the program tried to read a property called length (a piece of information a value carries) from something that is undefined.
  4. Line 2's output already showed it: Customer: undefined. The let on line 1 made the name but never gave it a value.

Line 3; the caret points at .length; the slip is that customer was never given a value, so it is undefined, and undefined has no length.

Check: give it a value on line 1, such as let customer = "Asha";, and line 3 prints Letters: 4. The runtime section of this lesson meets this message properly.

Worked example 2

This report has no output above it and different lines under its message. What does that tell you before you read anything else?

What we have: the report for a file whose first line looks fine

What we need: what kind of slip to look for

The plan: notice what is missing: no output at all, and a stack full of Node's own lines

comma.js

const total = 95
console.log("Total:" total);

Terminal

/home/asha/shop$ node comma.js
/home/asha/shop/comma.js:2
console.log("Total:" total);
            ^^^^^^^^

SyntaxError: missing ) after argument list
    at wrapSafe (node:internal/modules/cjs/loader:1713:18)
    at Module._compile (node:internal/modules/cjs/loader:1755:20)
    at Object..js (node:internal/modules/cjs/loader:1913:10)
    at Module.load (node:internal/modules/cjs/loader:1505:32)
    at Function._load (node:internal/modules/cjs/loader:1309:12)
    at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
    at node:internal/main/run_main_module:36:49

Node.js v22.23.1
  1. Nothing ran, not even line 1: the program could not be read. That is a SyntaxError, before you read the word SyntaxError.
  2. There is no line naming comma.js in the stack: the code never ran, so there is no place in it to name. All the at lines are Node's.
  3. The carets underline "Total:", the piece just before the place where the comma is missing.

A report with no output and no line of your own in its stack is a SyntaxError; here the missing comma after "Total:" is the slip.

Check: with the comma, console.log("Total:", total); prints Total: 95.

When you are stuck: a long report

Cover everything except the first line (where), the line with the caret, and the line with the kind and message.

Read those three, in that order, slowly.

Open the file at that line. Look at the character above the caret, then at the few characters just before it.

Skip every line that says node:internal: they are Node's own machinery and never hold your slip.

Your turn

A report begins with /home/asha/shop/marks.js:7 and its first at line ends in marks.js:7:15. Where do you look?Tap to reveal
  1. The first line names the file and the line: marks.js, line 7.
  2. The at line adds the column: 15.

Open marks.js at line 7, column 15.

Which lines of a Node report can you always skip?Tap to reveal
  1. Lines starting with at and naming node:internal belong to Node itself.

The node:internal lines.

A report shows two lines of output, then the error. What does the output tell you?Tap to reveal
  1. Output appears only from lines that ran.
  2. So everything up to the line that printed the second output worked.

That the program ran at least as far as the line that printed the second output; the slip is after it.

Did you know?

Why a terminal is still called a tty

The first terminals had no screen. They were teletypewriters: machines like typewriters, first used to send telegrams over wires. When people began to type commands to a computer, these machines became its input and output devices, because they were already on sale. The computer's answer came back printed on paper, a line at a time. The name stayed. On Linux today a terminal is still a tty, short for teletypewriter, and a command called tty prints the name of the terminal in use.

Why it fits here: The terminal window on the screen copies those machines: a line is typed, and the answer is printed below it.

Sources: Wikipedia: tty (Unix); Linus Akesson: The TTY demystified; Wikipedia: Computer terminal

The little arrow means it lacks

The mark ^ under an error has a name, the caret. The word is Latin and means it lacks, or there is lacking. Proofreaders use a caret when they check printed pages. They put it at the place where a word or a letter is missing, to show that something must be inserted there. Node uses the mark in the same spirit: the caret sits under the spot where the line stopped making sense.

Why it fits here: A caret in an error report points at the exact spot, as a proofreader's caret points at the gap in a line.

Sources: American Heritage Dictionary: caret; Oxford Learner's Dictionaries: caret; Wikipedia: Caret

The engine that left the browser

JavaScript is best known as the language of web pages, where an engine inside the browser reads it and runs it. Chrome's engine is called V8. In 2009 a programmer named Ryan Dahl wrote Node.js around that engine, so that the same language could run with no browser at all: from a terminal, on a file. Node's own guide still says it in one line. Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser.

Why it fits here: The command node on a terminal line starts this very engine, on the file named after it.

Sources: Node.js: Introduction to Node.js; Wikipedia: Node.js

In one line

Node's report gives the place (file:line, and line:column in the stack), the caret under the exact spot, and the kind and message; read those three first and skip Node's own node:internal lines.

The SyntaxError family

At a glance

JavaScript reads a whole program before it runs any line of it. When the reading breaks down, nothing runs at all, and the report is a SyntaxError. The word syntax means the order in which the pieces of a language are put together. A missing bracket, a quote that closes too early or a stray sign each breaks that order.

The message names what JavaScript found, or what it expected, at the point where it gave up. Each piece that it reads as one unit is called a token: a name, a number, a string or a symbol. So the words unexpected token mean a piece that could not come next. The real slip often sits just before the place named, and sometimes one line above it.

Take a guess: A program has ten good lines and one missing bracket on its last line: how many of its lines run?

Think of a teacher reading an answer sheet aloud. At some word the sentence stops making sense, and the teacher stops there: "I expected a full stop here, but I found a word." The teacher cannot see what you meant. The teacher can only say where the reading broke down and what was expected there.

A SyntaxError message is exactly that. JavaScript reads the whole program before running any of it. When the reading breaks down, it names what it found, or what it expected, at that point. Your job is to look at that point and just before it.

Each piece of code that JavaScript reads as one unit is a token: a name such as price, a number such as 40, a string such as "Asha", or a symbol such as (, + or ;. Most SyntaxError messages talk about tokens.

The messages, side by side

The messageWhat it meansThe usual slipAn example that gives it
missing ) after argument listinside the brackets of a call, it expected a comma or the closing bracket, and found something elsea missing comma between values, or a missing )console.log("Total:" 95);
Unexpected token ')'it found a ) where something else had to come firsta value missing before the bracket, or one bracket too manyconsole.log("Asha" + );
Unexpected token '='it found an = it could not usea space inside an operator, such as + =total + = 5;
Unexpected token '*'two operators in a rowa slip of the finger: +* instead of +console.log(1 +* 2);
Unexpected token ';'the line ended while a value was still neededa value left out after =let x = ;
Unexpected string or Unexpected numbera string or a number where it expected an operator or a commatwo values side by side with nothing between themlet x = "a" "b";
Invalid or unexpected tokena character it cannot read at allcurly quotes, a quote never closed, a name starting with a digitlet 2fast = 1;
Missing initializer in const declarationa const made with no valuethe = and the value forgottenconst total 5;
Identifier 'x' has already been declaredthe same name made twicea second let or const for a name that existsconst x = 1; const x = 2;

Read the left column as a teacher's remark. "Unexpected token ')'" means I was not expecting a bracket here. "missing ) after argument list" means I expected the list of values to end, or to continue with a comma. The word argument means a value handed to a call inside its brackets, as in lesson 1.

console.log("Asha" + );
Uncaught SyntaxError: Unexpected token ')'

Here + promises a second value, and the bracket arrives instead. So the bracket is unexpected. The slip is just before it: the missing second value.

let x = "a" "b";
Uncaught SyntaxError: Unexpected string

After the string "a", JavaScript expected an operator such as + or the end of the statement. It found another string. The message names what it found.

A common mistake

Fixing the token the message names, when the slip is just before it. In console.log("Asha" + ); the bracket is right; the missing value before it is the slip. Look at the named token and the piece before it.

A quote that closes too early

Watch what an apostrophe does inside single quotes.

console.log('It's here');
Uncaught SyntaxError: missing ) after argument list

The string starts at the first single quote and ends at the next one, the apostrophe in It's. So JavaScript reads the string 'It', then the name s sitting right after it with no comma. That is two values side by side, so it reports missing ) after argument list. The fix from lesson 1: use double quotes outside, "It's here".

When the line named is not the line with the slip

Sometimes the report names a line after the real slip. JavaScript joins lines together when a line is left unfinished, so it notices the trouble only further on.

let a = 5
let b = a +
console.log(b)
Uncaught ReferenceError: Cannot access 'b' before initialization
    at line 3

Line 2 ends with a + and no second value. JavaScript does not give up there: it takes the next line as the rest of the sum, so it reads let b = a + console.log(b). Running that, it needs b before b has been made, and stops on line 3. The trace says line 3; the slip is the unfinished line 2.

Look one line up

If the line named in a report looks perfect, look at the line before it. An unfinished line, a missing bracket or a quote left open often shows up only on the next line.

Worked example 3

A file stops with a SyntaxError. Read the caret and fix it.

What we have: a file with one line and Node's report

What we need: the slip and its fix

The plan: read where, then the caret, then the message; look at the caret's token and the one before it

shop.js

let total = 10
total + = 5;
console.log(total);

Terminal

/home/asha/shop$ node shop.js
/home/asha/shop/shop.js:2
total + = 5;
        ^

SyntaxError: Unexpected token '='
    at wrapSafe (node:internal/modules/cjs/loader:1713:18)
    at Module._compile (node:internal/modules/cjs/loader:1755:20)
    at Object..js (node:internal/modules/cjs/loader:1913:10)
    at Module.load (node:internal/modules/cjs/loader:1505:32)
    at Function._load (node:internal/modules/cjs/loader:1309:12)
    at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
    at node:internal/main/run_main_module:36:49

Node.js v22.23.1
  1. Where: line 2. The caret is under the =.
  2. The message says that = was not expected. Before it is a + and a space.
  3. The writer meant +=, an operator that adds to a name, or wanted total = total + 5. With a space inside, + and = are two separate tokens, and = cannot follow +.

shop.js

let total = 10
total = total + 5;
console.log(total);

Terminal

/home/asha/shop$ node shop.js
15

Write the sum out in full, total = total + 5;; the file then prints 15.

Check: 10 + 5 is 15, and nothing is left between + and = to confuse the reader.

Another way: the shorter operator += with no space, total += 5;, does the same job. The JavaScript step meets it properly.

Worked example 4

Two SyntaxErrors hide in this program. Fix them one at a time, running after each fix.

What we have: a two-line program with two slips

What we need: a program that prints Asha's marks: 87

The plan: fix the first slip the message names, run again, and read the new message

const name = “Asha”;
console.log(name "marks:", 87);
Uncaught SyntaxError: Invalid or unexpected token
  1. Invalid or unexpected token: a character JavaScript cannot read. On line 1, the quotes are curly ones, from a chat app. Retype them.
const name = "Asha";
console.log(name "marks:", 87);
Uncaught SyntaxError: missing ) after argument list
  1. A new message is progress: the first slip is gone. Now a comma is missing between name and "marks:".
const name = "Asha";
console.log(name, "marks:", 87);
Asha marks: 87

Straight quotes on line 1 and a comma after name on line 2: it prints Asha marks: 87.

Check: each run showed a different message until none was left, and the output has the three values with one space between each.

A path that fails: trying to fix both slips at once without running in between. With two changes, a new message cannot tell you which change caused it.

When you are stuck: a SyntaxError you cannot see

Read the message as a teacher's remark: what did it expect, and what did it find?

Look at the token the message or the caret names, then at the token just before it.

Count the pairs on that line: quotes, brackets. Then check the line above.

Still stuck? Delete half the program (copy it somewhere safe first). If the error goes, the slip was in the half you deleted. Lesson 3 makes this a method.

Your turn

What does Unexpected number suggest you look for?Tap to reveal
  1. A number turned up where JavaScript expected an operator, a comma or the end of the statement.

Two values side by side with nothing between them, such as let x = 5 6;; add the missing operator or comma.

console.log("Price", 40 "rupees");
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
Uncaught SyntaxError: missing ) after argument list
  1. After 40, JavaScript expected a comma or the closing bracket.
  2. It found a string instead, so it reports the list of values as unfinished.

SyntaxError: missing ) after argument list; the comma after 40 is missing.

Why does a SyntaxError never print the output of the lines before it?Tap to reveal
  1. JavaScript reads the whole program before running any line.
  2. If it cannot read the program, it runs none of it.

Because nothing runs until the whole program has been read.

Did you know?

A rocket lost to one missing bar

On 22 July 1962 NASA launched Mariner 1 towards Venus. It veered off course, and a safety officer destroyed it 293 seconds after launch. One cause was a tiny slip in the guidance program. An equation had been written by hand with a small bar over the letter R. When the equation was turned into code, the bar was left out, so the computer steered by moment-to-moment values in place of smoothed ones. The writer Arthur C. Clarke called it the most expensive hyphen in history. NASA notes that the missing mark was not a hyphen at all.

Why it fits here: One small mark can change what a program means. JavaScript's reader stops at the marks it can tell are missing, before anything runs.

Sources: NASA Science: Mariner 1; NASA Space Science Data Coordinated Archive: Mariner 1; Wikipedia: Mariner 1

Syntax is Greek for putting in order

The word syntax is far older than computers. It comes from ancient Greek, where syn means together and taxis means arrangement. The Greek verb behind it means to put in order. For a very long time the word belonged to grammar: the rules for the order of words in a sentence. Dictionaries now give it a second meaning as well: the rules for forming statements in a programming language. A SyntaxError, then, is an error of order.

Why it fits here: Each SyntaxError message is about order: a piece of code came where the rules of the language did not allow it.

Sources: American Heritage Dictionary: syntax; Wikipedia: Syntax

In one line

A SyntaxError says what JavaScript found or expected where its reading broke down. Look at that token and the one before it, and if the named line looks perfect, look one line up.

Messages from a running program

At a glance

Some errors come only while a program is running. Every line could be read, so the program started. Then one line met a value that was not what it needed, and the program stopped there with a message. The lines before it had already run.

Three ideas explain most of these messages. A value can carry information, read with a dot, such as the length of a piece of text. A name can hold nothing at all, which JavaScript calls undefined or null. A value can also do a job, run with a dot and brackets. Reading from nothing gives a TypeError, and so does calling a name that is not a job. A number outside the allowed limits gives a RangeError. Some surprises, such as NaN and Infinity, raise no error at all.

Take a guess: What does JavaScript answer when a sum divides 10 by 0: an error, or a value?

A SyntaxError stops a program before it starts. The messages in this section come later, while the program runs. Each one means that a line could be read perfectly well, but the value it worked on was not what the line needed. To read them, we need three small new ideas, one at a time.

New idea 1: a value can carry information, read with a dot

A string knows how many characters it has. You read that with a dot and the word length. A piece of information that a value carries, read with a dot, is called a property.

console.log("chai".length, "Asha Stores".length);
4 11

The space in Asha Stores counts as a character, so it has 11. Read "chai".length aloud as "the length of chai".

New idea 2: a name with nothing in it

In lesson 1, every let was given a value at once. You can also make a let with no value, meaning to fill it later. Until then it holds a special value called undefined: the empty jar.

let customer;
console.log(customer);
undefined

There is a second empty-looking value, null. A programmer writes null on purpose to mean there is deliberately nothing here, such as a seat that is not booked. undefined usually means nothing has been put here yet. Both have one thing in common: they carry no properties at all.

The most common error in JavaScript

Now put the two ideas together. Ask an empty jar for its length.

let customer;
console.log(customer.length);
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
    at line 2

Read the message slowly. Cannot read properties of undefined: something on this line was undefined, and the program tried to read a property from it. (reading 'length'): the property it was trying to read was length. So look on line 2 for a dot followed by length, and ask what was to the left of the dot. It was customer, and customer was never given a value.

This message, with null or undefined, and with every possible property name, is the most common error in JavaScript code. In real programs it usually means some data did not arrive: a form left empty, a search with no results, a server that sent nothing back.

const seat = null;
console.log(seat.length);
Uncaught TypeError: Cannot read properties of null (reading 'length')
    at line 2

Reading the empty-value message

The word after of is what the value was: undefined or null. The word after reading is the property it asked for. Find that property after a dot on the named line; the thing before the dot is the empty one.

New idea 3: a value can do a job, run with a dot and brackets

Some properties are methods: jobs a value can do. You run one with a dot, its name and a pair of brackets, just as console.log(...) runs the console's log job. A string can give back a copy of itself in capital letters, and a number can round itself for printing.

console.log("Asha Stores".toUpperCase());
console.log((5.678).toFixed(2), (5.678).toFixed(1));
ASHA STORES
5.68 5.7

toFixed(2) means "rounded to 2 places after the decimal point, as text". Lesson 1 promised a way to round for printing; this is it. The brackets around 5.678 stop JavaScript from reading the dot as a decimal point.

When a name is not a job

Spell a method wrongly and the value has no such job. Its property of that name is undefined, and undefined cannot be run.

const shop = "Asha Stores";
console.log(shop.toUppercase());
Uncaught TypeError: shop.toUppercase is not a function
    at line 2

The message names exactly what was run: shop.toUppercase. Compare it letter by letter with the real name, toUpperCase, with a capital C. Capitals count, as always. The same message appears if you put brackets after a value that is not a job at all.

const total = 40;
total();
Uncaught TypeError: total is not a function
    at line 2

RangeError: a value outside what is allowed

A fourth kind of error, RangeError, means a number was outside the range a job accepts. toFixed accepts from 0 to 100 places, so asking for 200 is out of range.

console.log((5.678).toFixed(200));
Uncaught RangeError: toFixed() digits argument must be between 0 and 100
    at line 1

The message even states the allowed range. Another job, repeat, makes a string repeat itself a number of times; a negative count makes no sense.

console.log("ha".repeat(3));
console.log("ha".repeat(-1));
hahaha
Uncaught RangeError: Invalid count value: -1
    at line 2

Not every surprise is an error

Some wrong-looking results come with no message at all. JavaScript gives a value and carries on, which makes them harder to notice than an error.

console.log(10 / 0, 0 / 0, "abc" * 2, undefined + 1);
Infinity NaN NaN NaN

Dividing by zero gives Infinity. Zero divided by zero, text times a number and undefined plus one all give NaN. A NaN in your output is a clue, just like an error: some value on the way was not the number you thought. Print the values one by one to find which.

Worked example 5

A shop's welcome line breaks. Read the message and fix it.

What we have: a program and its error

What we need: the welcome line printed

The plan: find the property after reading, look for it after a dot on line 3, and ask what was before the dot

let shopName;
const greeting = "Welcome to ";
console.log(greeting + shopName.toUpperCase());
Uncaught TypeError: Cannot read properties of undefined (reading 'toUpperCase')
    at line 3
  1. The property is toUpperCase. On line 3 it comes after shopName..
  2. So shopName was undefined. Line 1 made it with let and no value.
let shopName = "Asha Stores";
const greeting = "Welcome to ";
console.log(greeting + shopName.toUpperCase());
Welcome to ASHA STORES

Give shopName a value when it is made; the line prints Welcome to ASHA STORES.

Check: the message named toUpperCase and undefined, and the fix gave the name before the dot a value.

Worked example 6

A price shows as 5.678 rupees and must be printed to 2 places. A developer tried (5.678).tofixed(2). What happens, and what is the fix?

What we have: the method name spelt with a small f

What we need: the price as 5.68

The plan: predict the message from the spelling, then use the exact name

console.log((5.678).tofixed(2));
Uncaught TypeError: 5.678.tofixed is not a function
    at line 1
  1. The number has no job called tofixed, with a small f, so that property is undefined, and undefined cannot be run.
console.log((5.678).toFixed(2));
5.68

Spell it toFixed, with a capital F; it prints 5.68.

Check: 5.678 rounded to 2 places is 5.68, because the third place, 8, rounds the second up.

A path that fails: adding brackets, quotes or spaces somewhere else on the line. The message named the exact thing that is not a function, tofixed, so the fix is there and nowhere else.

Worked example 7

A results portal prints a percentage as NaN, with no error. Find where the NaN comes from.

What we have: a program that prints NaN

What we need: the slip that produced NaN

The plan: print each value on the way, with its typeof

const marks = 412;
const maximum = "five hundred";
console.log(marks / maximum * 100);
NaN
  1. No error, so no line is named. Print each value and its type:
const marks = 412;
const maximum = "five hundred";
console.log(marks, typeof marks);
console.log(maximum, typeof maximum);
412 number
five hundred string
  1. The maximum is text in words, which cannot be read as a number, so the division gives NaN.
const marks = 412;
const maximum = 500;
console.log(marks / maximum * 100);
82.39999999999999
  1. The long tail is the decimal surprise from lesson 1. Round it for printing:
const marks = 412;
const maximum = 500;
console.log((marks / maximum * 100).toFixed(1));
82.4

The maximum was the text five hundred; with the number 500 it prints 82.4.

Check: 412 ÷ 500 = 0.824, and 0.824 × 100 = 82.4.

A path that fails: staring at the formula. The formula was right all along; only printing the values showed which one was wrong.

When you are stuck: a runtime message

Find the line in the trace. Then find the word the message names: the property after reading, or the thing that is not a function.

Look at what is to the left of the dot. Print it: console.log(customer). If it prints undefined or null, find where it should have been given a value.

For is not a function, compare the name letter by letter with the real one, capitals included.

For NaN with no error, print every value on the way, with typeof.

Your turn

let city;
console.log(city);
console.log(city.length);
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
undefined
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
    at line 3
  1. Line 2 prints the empty value, undefined.
  2. Line 3 asks undefined for its length, which it does not have.

It prints undefined, then the TypeError at line 3.

What does "Pune".length give, and why is it not an error?Tap to reveal
  1. A string carries its length as a property.
  2. Pune has 4 characters.

4: the value is a string, which has a length; only undefined and null have no properties.

Which kind of error says a number was outside what a job accepts?Tap to reveal
  1. (1.5).toFixed(200) is an example.

A RangeError.

Did you know?

The billion-dollar mistake

The idea of a name that refers to nothing has an inventor, and he is sorry for it. In 1965 the British computer scientist Tony Hoare was designing a language called ALGOL W. He added the null reference, a way for a name to refer to nothing, because it was so easy to build. At a conference in 2009 he called it his billion-dollar mistake. He said it had led to countless errors and crashes over forty years.

Why it fits here: The message Cannot read properties of null is this old idea at work: a name that refers to nothing was asked for something.

Sources: InfoQ: Null References, The Billion Dollar Mistake (Tony Hoare's talk); Wikipedia: Tony Hoare

A bug too old to fix

Ask JavaScript what kind of thing null is, with the word typeof, and it answers object, its name for a bundle of values. The answer is wrong, and it is a well-known bug. It comes from the first JavaScript ever written. Each value was stored with a small tag that told its type, and the tag for objects was 0. Null was stored as a plain zero, so it looked like an object. A fix was proposed years later and was rejected. It would have changed the answer to null.

Why it fits here: The messages of this topic speak of undefined and null, the two empty values. This bug shows how null was stored in the first JavaScript.

Sources: MDN: typeof; Alexander Ellis: typeof null, investigating a classic JavaScript bug

The video that outgrew its counter

YouTube once counted the views of a video with a 32-bit integer, a whole number kept in a fixed amount of memory. The largest value it could hold was 2,14,74,83,647, about 214.7 crore. Nobody expected a video to be watched that many times. Then the song Gangnam Style was. In December 2014 YouTube announced that the video had passed the limit. Its engineers had seen it coming and had already changed the counter to a 64-bit integer, which can count past nine quintillion.

Why it fits here: A RangeError is the same trouble met in time: a number is asked to go beyond what its place can hold.

Sources: BBC News: Gangnam Style music video 'broke' YouTube view limit; Wikipedia: Gangnam Style

In one line

Cannot read properties of undefined (or null) means the thing before the dot is empty. Is not a function means the name is not a job: check its spelling. A RangeError means a number was out of range. NaN and Infinity arrive quietly, so print the values to find them.

The browser's console

At a glance

Every web browser keeps a console, a panel hidden from ordinary visitors. It is one of the developer tools, called DevTools in Chrome, and the key F12 opens it. The console shows the messages and errors of the page that is open, each with a link to the line that caused it. A line of JavaScript typed there runs at once, so the console is also a place to try things.

Each browser runs JavaScript with its own engine: V8 in Chrome and Edge, SpiderMonkey in Firefox, JavaScriptCore in Safari. The engines word the same error in different ways. The slip behind the words is the same, and so is the fix.

Take a guess: Do Chrome and Firefox use the same words for the same error?

Every web page you visit runs JavaScript, and every browser keeps a console for it, hidden from ordinary visitors. Developers open it all day long: to see a page's messages and errors, and to try a line of code on the spot. In Chrome it lives in the DevTools, short for developer tools.

To open the console in Chrome or EdgePress
on Windows or LinuxF12, or Ctrl + Shift + J to go straight to the Console tab
on a MacCmd + Option + J
from the menuthe three dots, then More tools, then Developer tools, then the Console tab

The console shows a > sign at its bottom line. That is its prompt. Type a line of JavaScript there and press Enter, and it runs at once, on that page. Try 40 + 55 and it answers 95. It is the same language as on these pages, in the same browser.

Errors from the page appear in red. Each starts with Uncaught and the kind and message you already know. On the right of the red line, Chrome shows where: the file and the line, as a link. Click it, and Chrome opens the file in its Sources tab with that line marked. That link plays the same part as the first line of Node's report.

Try it: a page with a hidden error

This block is a small web page in HTML, the language of web pages that the HTML step teaches. Its script prints one line and then makes a slip. Press Run: the page appears below the block. Then open the console and look for its two messages.

<p>This page printed two messages. Open the console to see them.</p>
<script>
  console.log("The page has loaded");
  consol.log("A second message");
</script>

The Console shows

Error    Uncaught ReferenceError: consol is not defined

In the console you will find the first message, then a red Uncaught ReferenceError: consol is not defined. The page itself looks perfectly fine. That is why the console matters. On a real website, a broken button often shows nothing at all to the visitor. The only sign of the slip is a red line in the console.

Same slip, different words

The part of a browser that runs JavaScript is its engine. Chrome and Edge use an engine called V8, and so does Node. Firefox uses SpiderMonkey, and Safari uses JavaScriptCore. All three follow the same rules for the language, so the same code does the same thing. But each engine writes its own error messages.

MDN, the web's best-known reference for JavaScript, keeps a page for every error message with the wording of each engine. For reading a property of undefined, it lists these:

EngineThe message
V8 (Chrome, Edge, Node)TypeError: Cannot read properties of undefined (reading 'x')
SpiderMonkey (Firefox)TypeError: "x" is undefined
JavaScriptCore (Safari)TypeError: undefined is not an object (evaluating 'obj.x')

Three wordings, one slip: something was undefined, and a property was read from it. Once you know the meaning, you can read any of them. The outputs shown on these pages are V8's, checked in Chrome and in Node. If you press Run in Firefox or Safari, the message is that browser's own, while the slip and the fix are the same.

Why V8 matters so much

V8 runs JavaScript in Chrome and Edge, which most people use, and in Node, which runs a large share of the web's servers. So V8's wording is the one you will meet most often, and the one most search results quote.

Worked example 8

A friend using Safari sees TypeError: undefined is not an object (evaluating 'order.total'). What does it mean, and what would Chrome say?

What we have: Safari's wording of an error

What we need: its meaning, and V8's wording of the same slip

The plan: match the Safari pattern from the table, then rewrite it in V8's pattern

  1. Safari's pattern is undefined is not an object (evaluating 'something.property').
  2. Here the something is order and the property is total: the code read order.total while order was undefined.
  3. V8's pattern puts the property after reading.

It means order was undefined when order.total was read. Chrome would say TypeError: Cannot read properties of undefined (reading 'total').

Check: both wordings name undefined and the property total, so they describe the same slip.

Worked example 9

Run a line in the console to find out what kind of value something is, without changing the page.

What we have: the browser's console on any page

What we need: the type of the value "12" * 2

The plan: type the expression at the prompt; the console prints the result, and typeof prints its type

  1. Open the console with Ctrl + Shift + J (Cmd + Option + J on a Mac).
  2. Type the lines below one at a time, pressing Enter after each. The block shows the same lines here, with the output a console.log would give.
console.log("12" * 2);
console.log(typeof ("12" * 2));
24
number

It is the number 24: * turned the text into a number, as lesson 1 showed.

Check: the console's answer and this block's output agree, because both run in V8 in Chrome.

Another way: at the console prompt you can leave out console.log: typing "12" * 2 alone shows 24, because the console prints the value of whatever you type.

When you are stuck: the console

Nothing in the console? Reload the page with the console open: some messages are printed only while the page loads.

Too many messages? Type a word in the console's Filter box to show only the lines that contain it, or choose Errors from its levels menu.

The message is in another wording? Look it up on MDN's error reference: each page lists the wordings of all three engines.

Your turn

Which engine runs JavaScript in Chrome, in Edge and in Node?Tap to reveal
  1. The three share one engine.

V8.

A button on a website does nothing when clicked, and no message appears on the page. Where do you look first?Tap to reveal
  1. A slip in a page's script rarely shows on the page itself.
  2. The browser records it in red in the console.

In the console (F12, or Ctrl + Shift + J).

Firefox says TypeError: "seat" is undefined. Which property of seat might the code have been reading, and how would you find out?Tap to reveal
  1. Firefox's wording names the empty value, seat, but not the property.
  2. The file and line link on the right leads to the line; on it, look for seat followed by a dot.

Follow the link to the line and read the property after seat.; V8 would have named it in its message.

Did you know?

Firebug, the tool that started it

Early web developers hunted for bugs the slow way: they commented out code and tried again. In January 2006 Joe Hewitt, one of the makers of Firefox, released a small add-on called Firebug. Its first version was a single console panel, and his note with it said that the code was only a few days old. Mozilla calls Firebug the first tool that let programmers inspect, edit and debug code right in the Firefox browser. Developer tools are now a built-in part of every large browser.

Why it fits here: The console in today's browsers does the job that Firebug's first panel did: it shows a page's messages and errors as they happen.

Sources: Mozilla Hacks: Saying goodbye to Firebug; Wikipedia: Firebug (software); Wikipedia: Web development tools

The oldest engine was rewritten at home

The engine inside Firefox, SpiderMonkey, is the oldest of them all. It was the first JavaScript engine, written by Brendan Eich, the man who created the language. He has told the story himself. The first version, called Mocha, took ten days in May 1995 and was written in a hurry. Later he stayed home for two weeks and rewrote Mocha as the code that became SpiderMonkey. He did it partly as a small strike against managers who gave JavaScript too little support.

Why it fits here: Chrome, Firefox and Safari each have an engine with a history of its own, which is why each words the same error in its own way.

Sources: Brendan Eich: New JavaScript Engine Module Owner; Wikipedia: SpiderMonkey

In one line

The browser's console (F12) shows a page's messages and errors, with a link to the line, and runs any line you type. Each engine words errors its own way, but the slip and the fix are the same.

Where it is used

Reading error reports is not a beginner's skill that you grow out of. It is the skill senior developers use most. Here is where each part of this lesson turns up in real work.

What you learnedWhere it is usedA real example
Node's report: file:line and the caretevery server, script and build tool written in JavaScripta payment server stops at night; the log's first line names the file and line, and the on-call developer opens exactly that line
the stack's first line of your ownlong reports from big programs, where most lines belong to librariesa report of 40 lines, of which 38 name node_modules or node:internal; the 2 lines naming the project's own files hold the slip
Cannot read properties of undefinedany code that handles data from outside: forms, servers, filesa train booking page breaks when a passenger leaves the age box empty, because the code reads a property of the missing value
is not a functionevery misspelt or missing methodan app updated a library that renamed one of its jobs; every old call now says is not a function, and the library's change notes give the new name
RangeErrorjobs with limits on their numbersa report asks toFixed for more places than it allows; a page tries to make a list of negative length
the browser's consoleweb pages, web apps and browser extensionsa Chrome extension's button does nothing; the console of its popup shows the red line that explains why (the browser extensions step)
engine wordingstesting a site in more than one browsera bug report from a Safari user quotes undefined is not an object; the developer, on Chrome, translates it to V8's wording and finds the line
searching a messageevery day, at every levela developer pastes the fixed words of a new library's error into a search, finds the project's GitHub issue, and learns that a newer version fixes it

Mistakes and debugging

These are the mistakes people make while reading errors, which cost more time than the errors themselves.

1. Reading only the first word

TypeError is a family of dozens of messages. The useful part is the detail after the colon. Always read the message to its end, slowly, word by word.

2. Looking at the wrong line

A long report names many lines. The one to open is the first line naming your file: the very first line of Node's report, or the first at line that is not node:internal and not a library. And remember the unfinished-line case: if the named line looks perfect, look one line up.

3. Trusting what you meant instead of what you wrote

You read toUppercase and your mind sees toUpperCase, because you know what you meant. The computer reads what is there. Compare letter by letter, or copy the real name from the docs and paste it over yours.

4. Fixing the symptom, not the cause

let city;
console.log(city.length);
Uncaught TypeError: Cannot read properties of undefined (reading 'length')
    at line 2

The quick patch is to delete line 2. The error goes, and so does the feature. The real question is why is city undefined here? Find the place where it should have been given a value. Fix that, and the error goes for the right reason.

5. Changing many things at once

After three changes, a new message cannot tell you which change caused it. Make one change, run, read. A different message after a fix is progress: the old slip is gone and the next one is showing.

6. Ignoring a quiet NaN

const items = 3;
const rate = "40 rupees";
console.log("Bill:", items * rate);
Bill: NaN

No error, so it is easy to shrug and move on. But NaN is as clear a message as any red line: a value on the way was not a number. Here "40 rupees" cannot be read as a number, because of the word rupees. Keep the number and the unit apart: const rate = 40;.

The debugging corner: let the report do the work

Before changing anything, write down in one sentence what the report says: "line 3, reading length of undefined". That sentence is your target. Most slips are found the moment the sentence is written, because it tells you exactly which value to print.

Quick card

The lesson on one card.

In a report, findIt looks likeIt tells you
where/home/asha/shop/bill.js:4the file and the line
the careta ^ under the line of codethe exact spot on that line
the kind and messageReferenceError: bill is not definedwhat went wrong
the stackat Object.<anonymous> (/home/asha/shop/bill.js:4:26)file, line and column; skip the node:internal lines
the versionNode.js v22.23.1which Node ran it; give it when asking for help
The messageLook for
missing ) after argument lista missing comma or ) in a call
Unexpected token, string or numberthe named token and the one before it; two values with nothing between
Invalid or unexpected tokencurly quotes, an unclosed quote, a name starting with a digit
Identifier has already been declareda name made twice
is not defineda misspelt name, or a name never made
Cannot access before initializationa name used above the line that makes it
Cannot read properties of undefined (reading 'x')the thing before .x is empty: find why
is not a functionthe spelling of the job, capitals included
RangeErrora number outside what the job accepts
NaN or Infinity, no errorprint each value with typeof

Searching: the kind and the fixed words, without your own names, plus javascript or node; MDN's error reference first; check the date and version of answers; never paste a secret.

The story: The red line is a map

You read the red line again, slowly, part by part. The first word names the kind of trouble. The next words say what the trouble is. The number points to the line of the script where it began.

You open the lamp's script at that line, and there it is: a name spelt one way above and another way below. You fix one letter. The window clears, and the time comes back: half past nine.

Corin puts his hammer away. "So the red marks are a map," he says. Ilse almost smiles. "They always were."

Reagents gathered: terminal, prompt, error message, caret, stack trace.

Sources