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
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 know | A tiny example | Where 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 functionand 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.
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.
| Part | Here | What it tells you |
|---|---|---|
| 1. Output before the error | Bill: 120 | the program ran up to line 3 without trouble |
| 2. Where: the file and the line | /home/asha/shop/bill.js:4 | the file, then a colon, then the line number: line 4 of bill.js |
| 3. The line itself, with a caret under it | the line of code, then a ^ under bill | the exact spot on that line where the computer stopped |
| 4. The kind and message | ReferenceError: bill is not defined | what went wrong, as in lesson 1 |
| 5. The stack: lines starting with at | the first at line names bill.js:4:26; the rest name node:internal | the first one is yours: file, line 4, column 26. The node:internal ones are Node's own machinery: skip them. |
| 6. The version | Node.js v22.23.1 | which 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
- Where: name.js:3, so line 3.
- The caret is under the dot before
length, at column 34. - The message: the program tried to read a property called length (a piece of information a value carries) from something that is
undefined. - Line 2's output already showed it: Customer: undefined. The
leton 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
- Nothing ran, not even line 1: the program could not be read. That is a SyntaxError, before you read the word SyntaxError.
- 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.
- 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
- The first line names the file and the line: marks.js, line 7.
- 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
- 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
- Output appears only from lines that ran.
- 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 message | What it means | The usual slip | An example that gives it |
|---|---|---|---|
missing ) after argument list | inside the brackets of a call, it expected a comma or the closing bracket, and found something else | a missing comma between values, or a missing ) | console.log("Total:" 95); |
Unexpected token ')' | it found a ) where something else had to come first | a value missing before the bracket, or one bracket too many | console.log("Asha" + ); |
Unexpected token '=' | it found an = it could not use | a space inside an operator, such as + = | total + = 5; |
Unexpected token '*' | two operators in a row | a slip of the finger: +* instead of + | console.log(1 +* 2); |
Unexpected token ';' | the line ended while a value was still needed | a value left out after = | let x = ; |
Unexpected string or Unexpected number | a string or a number where it expected an operator or a comma | two values side by side with nothing between them | let x = "a" "b"; |
Invalid or unexpected token | a character it cannot read at all | curly quotes, a quote never closed, a name starting with a digit | let 2fast = 1; |
Missing initializer in const declaration | a const made with no value | the = and the value forgotten | const total 5; |
Identifier 'x' has already been declared | the same name made twice | a second let or const for a name that exists | const 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
- Where: line 2. The caret is under the =.
- The message says that = was not expected. Before it is a + and a space.
- 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
- 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
- A new message is progress: the first slip is gone. Now a comma is missing between
nameand"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
- 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
- After 40, JavaScript expected a comma or the closing bracket.
- 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
- JavaScript reads the whole program before running any line.
- 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
- The property is toUpperCase. On line 3 it comes after
shopName.. - So
shopNamewas undefined. Line 1 made it withletand 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
- 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
- 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
- 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
- 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
- Line 2 prints the empty value, undefined.
- 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
- A string carries its length as a property.
- 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.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 Edge | Press |
|---|---|
| on Windows or Linux | F12, or Ctrl + Shift + J to go straight to the Console tab |
| on a Mac | Cmd + Option + J |
| from the menu | the 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:
| Engine | The 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
- Safari's pattern is undefined is not an object (evaluating 'something.property').
- Here the something is
orderand the property istotal: the code readorder.totalwhileorderwas undefined. - 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
- Open the console with Ctrl + Shift + J (Cmd + Option + J on a Mac).
- 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
- 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
- A slip in a page's script rarely shows on the page itself.
- 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
- Firefox's wording names the empty value, seat, but not the property.
- 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.
Searching for an error message
At a glance
Almost every error message has been met by thousands of people before, and many of them asked about it in public. So a well-made search finds the answer. Such a search keeps the kind of error and the fixed words of the message. It drops the names that belong to one program alone, and it adds the name of the language or the tool. Quotation marks around the message keep its words together.
Good answers live in a few places: MDN's reference for JavaScript errors, the official documents of a tool, Stack Overflow, and the issue pages on GitHub. The date and the version of an answer matter, because tools change. A question to other people works best with four things in it: what was wanted, what happened, the smallest code that shows it, and what was tried.
Take a guess: Which finds more help: a search with your own file names in it, or one without them?
Picture asking at a big railway station: "My train is late." Nobody can help, because a thousand trains run every day. Now ask: "Is train 12128, the Pune to Mumbai Intercity, late today?" That question has an answer. A search for an error works the same way: say exactly which error, and leave out what only you would know.
Almost every error message you will ever see has been met by thousands of people before you, and many of them asked about it in public. So a well-made search finds an answer within minutes. A badly made one finds nothing, or finds answers to a different problem.
Making the search
- Copy the kind and the message exactly, as text. Do not retype it from memory: one changed word sends the search elsewhere.
- Take out what is yours alone: your variable names, your file names, your folders and your numbers. Nobody else has a variable called
shopName. - Keep the fixed words of the message, the part every person who meets it sees.
- Add the tool: javascript, node, or the name of the library, so that the results are about the right language.
- Put the message in quotes if the results are too broad: most search engines then look for those exact words together.
| The message you saw | A good search |
|---|---|
TypeError: Cannot read properties of undefined (reading 'shopName') | javascript "Cannot read properties of undefined (reading" |
TypeError: shop.toUppercase is not a function | javascript toUppercase is not a function |
SyntaxError: missing ) after argument list | javascript "missing ) after argument list" |
RangeError: toFixed() digits argument must be between 0 and 100 | javascript toFixed digits argument must be between 0 and 100 |
Look at the second row. Here the name toUppercase is kept, because it is a misspelling of a real method, and the search engine will often suggest the right one. Your own names are dropped; the names of the language's own jobs are kept.
Where the good answers are
| Place | What it is | How to use it |
|---|---|---|
| MDN's JavaScript error reference | one page for every error message, with what it means, the wording of each engine, and examples | the first place to read: it explains the message, not one person's program |
| Stack Overflow | a question and answer site where developers ask about real problems; answers are voted up or down | check that the question matches your situation; read the accepted answer and the highest-voted one; look at the date |
| The official docs of a tool | for Node, nodejs.org/docs; for a library, its own site | for messages that come from a tool rather than from JavaScript itself |
| GitHub issues | the bug lists of open-source projects | for messages from a library: someone may have reported the same problem, with a fix or a newer version |
A common mistake
Pasting an answer's code without reading it. An answer fixes the asker's program, which is never quite yours. Read why the answer works, then make the same change in your own code, by hand, one step at a time.
Check the date and the version of an answer. JavaScript, Node and every library change over the years. An answer from 2014 may describe a message worded differently, or a fix that the language has since replaced. The version line at the end of Node's report, such as Node.js v22.23.1, tells you which version you are on.
Never paste a secret
Some error messages and logs contain passwords, API keys or tokens: long strings of letters and digits that unlock an account. Never paste those into a search box, a forum or a chat. Replace them with a word such as SECRET first. A key once posted in public must be treated as stolen and replaced.
Asking for help well
If searching does not solve it, ask a person: a friend, a forum or a teacher. A good question gets a fast answer. Give four things:
- What you wanted: "I want the bill printed with tax."
- What happened instead: the full error report, copied as text, not a photo of the screen.
- The smallest code that shows it: a few lines, not the whole project. Lesson 3 shows how to cut a program down.
- What you tried, and the version: "I checked the spelling; Node v22.23.1."
Worked example 10
Turn this message into a search: TypeError: Cannot read properties of null (reading 'seatNumber'), from a file called booking.js.
What we have: the full message and the file name
What we need: a search that finds answers about this kind of error
The plan: keep the fixed words, drop what is ours, add the language
- The fixed words: Cannot read properties of null (reading.
- Ours alone: seatNumber and booking.js. Both go.
- Add the language: javascript. Quotes keep the fixed words together.
javascript "Cannot read properties of null (reading".
Check: every person who met this error saw those exact words, whatever their property was called, so the results are about this error.
A path that fails: searching the whole line, seatNumber and booking.js included. Few pages contain those exact names, so the useful pages drop out of the results.
Worked example 11
A Stack Overflow answer from 2015 says to fix your error by adding a line that starts with var. Should you use it as it is?
What we have: an old answer that uses var, which this school has not used
What we need: a decision, with a reason
The plan: check the date, and compare the answer's code with what the course teaches today
- The answer is from 2015.
letandconstarrived in the language that same year and are now what everyone uses. varis the older way of making a name; it still works, but it has surprises thatletandconstwere made to remove.- So the idea of the answer may be right, but its code is from an older style.
Use the idea, not the code as it is: write the same fix with let or const.
Check: a newer answer on the same question, or MDN's page, will show the fix in today's style; the JavaScript step explains var's surprises.
When you are stuck: a search finds nothing useful
Remove more of your own words: names, numbers, paths.
Try the message without its first word, or with node instead of javascript.
Read MDN's error reference page for the kind of error: it explains the meaning even when no one has your exact case.
Cut your program down to the few lines that still show the error (lesson 3). Often you spot the slip yourself on the way, and if not, you now have the perfect question to ask.
Your turn
Make a search for ReferenceError: totalMarks is not defined.Tap to reveal
- totalMarks is your own name: drop it.
- Keep is not defined, and the kind.
javascript "ReferenceError" "is not defined" (and the most likely slip is the spelling of totalMarks).
Which four things make a good question for help?Tap to reveal
- Think of what the helper needs to see your problem without your laptop.
What you wanted, what happened (the full message as text), the smallest code that shows it, and what you tried with the version.
An error log has a line that starts api_key= and goes on with a long string of letters and digits. What do you do before posting the log?Tap to reveal
- That is a secret key.
Replace the key with a word such as SECRET; never post it.
Did you know?
A help site named after an error
Stack Overflow, a question and answer site for programmers, is named after an error. A program keeps a stack, a pile of the jobs it has begun and not yet finished. When the pile needs more room than it has, the stack is said to overflow, and the program usually crashes. Jeff Atwood and Joel Spolsky created the site in 2008. They did not pick the name alone. The readers of Atwood's blog, Coding Horror, chose it by vote in April 2008.
Why it fits here: The site is one of the places where the good answers to error messages live, and its own name is an error.
Sources: Jeff Atwood, Coding Horror: Introducing Stackoverflow.com; Wikipedia: Stack Overflow; Wikipedia: Stack overflow
Explain it to a rubber duck
Programmers have a famous trick for getting unstuck, and it needs a toy. Put a rubber duck on the desk. Explain to the duck what the code is supposed to do, then go through the code line by line. At some point you say what a line does, and you notice that it is not what the line really does. The duck has said nothing at all. The name comes from a story in a book, The Pragmatic Programmer, by Andy Hunt and Dave Thomas.
Why it fits here: Writing a good question does the same work: by the time the four things are written down, the answer often shows itself.
Sources: rubberduckdebugging.com; Wikipedia: Rubber duck debugging
MDN began as a wiki called DevMo
MDN, the reference that this topic sends a search to first, has a history of its own. Mozilla, the maker of Firefox, launched it in 2005 as a wiki named DevMo. A wiki is a site that its readers can edit, so the pages were written by a community. In 2010 it was renamed the Mozilla Developer Network, MDN for short. From 2017, other large technology companies began to write for it and to support it as well.
Why it fits here: MDN's page for each JavaScript error is the first place to read about a message, and many hands keep its pages right.
Source: MDN: About MDN
In one line
Search the kind and the fixed words of the message, without your own names, plus the language. Read MDN first, check the date and version of any answer, never paste a secret, and ask with the four things a helper needs.
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 learned | Where it is used | A real example |
|---|---|---|
| Node's report: file:line and the caret | every server, script and build tool written in JavaScript | a 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 own | long reports from big programs, where most lines belong to libraries | a 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 undefined | any code that handles data from outside: forms, servers, files | a 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 function | every misspelt or missing method | an 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 |
| RangeError | jobs with limits on their numbers | a report asks toFixed for more places than it allows; a page tries to make a list of negative length |
| the browser's console | web pages, web apps and browser extensions | a Chrome extension's button does nothing; the console of its popup shows the red line that explains why (the browser extensions step) |
| engine wordings | testing a site in more than one browser | a 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 message | every day, at every level | a 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, find | It looks like | It tells you |
|---|---|---|
| where | /home/asha/shop/bill.js:4 | the file and the line |
| the caret | a ^ under the line of code | the exact spot on that line |
| the kind and message | ReferenceError: bill is not defined | what went wrong |
| the stack | at Object.<anonymous> (/home/asha/shop/bill.js:4:26) | file, line and column; skip the node:internal lines |
| the version | Node.js v22.23.1 | which Node ran it; give it when asking for help |
| The message | Look for |
|---|---|
| missing ) after argument list | a missing comma or ) in a call |
| Unexpected token, string or number | the named token and the one before it; two values with nothing between |
| Invalid or unexpected token | curly quotes, an unclosed quote, a name starting with a digit |
| Identifier has already been declared | a name made twice |
| is not defined | a misspelt name, or a name never made |
| Cannot access before initialization | a 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 function | the spelling of the job, capitals included |
| RangeError | a number outside what the job accepts |
| NaN or Infinity, no error | print 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
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)
- The Node.js documentation (Not stated for the docs in the Node.js LICENSE file (read 2026-10-26); facts and ideas only)
- The ECMAScript language specification (ECMA-262) (Ecma International copyright; facts and ideas only)
- Stack Overflow (Not confirmed from the site (its help page could not be fetched, 2026-10-26); facts and ideas only)