T3 Browser DevTools · Lesson 2
The Console
Reading the page's logbook: message levels and filters; writing useful messages with log, table, group, count, time and assert; reading an error to the end; asking the running page questions; and a method for any script problem.
- read the Console: its levels, its filters, and where each message came from
- write useful messages with console.log, table, group, count, time and assert
- read an error message in full, and use its stack trace
- ask the page questions by typing into the Console
- follow a method for any script problem, silent ones too
The back cover
Every web page keeps a diary, whether its author meant it to or not. Scripts write to it, and the browser writes to it when a file is missing or something breaks. Most people never open it, and so they guess at problems the diary has already named.
These pages show how to read that diary: the levels, the filters and the first red line. They show how to write useful messages with log, table, count, time and assert. They show how to read an error and its stack trace to the end, and how to ask the running page questions. They end with a method that finds a bug with or without an error.
Before you start
The story: The panel that said nothing
The ferry timetable at the Ferry Steps has gone blank. Passengers stand in front of an empty panel and argue about the tide. Through your new lens, every rule looks right, and the frame is there, with an empty list inside it. Corin taps the glass, as if that might help.
Ottilie Sen takes the lens from your hand and turns it over. On its back is a second glass, and on that glass, lines of small writing are scrolling past.
"Every machine in this city keeps a diary," she says. "Most people never read it. This one has been telling you what went wrong all morning." One of the lines is red.
The Elements panel answers "why does it look wrong?" This panel answers "why does it not work?" When a script on a page fails, the visitor often sees nothing at all: a button that does nothing, a list that stays empty. The browser knows exactly what went wrong, and it says so in one place. This lesson teaches you to read that place, write to it, and talk through it. It builds on these ideas; each has a tiny example.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| JavaScript runs in the page. | console.log("Rice"); prints Rice. | In a browser, the print goes to the Console panel. |
| A value has a type. | "60" is text, and 60 is a number. | Many errors come from the wrong type. |
| A script can read the page. | document.querySelector("h1") finds an element. | It gives null if nothing matches, a very common cause of errors. |
| The page is read from top to bottom. | A script runs when the browser reaches it. | A script placed too early finds nothing. |
| Elements have properties. | heading.textContent is its text. | Reading a property of null is an error. |
| Errors have names. | SyntaxError, TypeError. | The name tells you the kind of problem. |
| The Elements panel. | $0 is the selected node. | The Console can ask questions of it. |
| The Drawer. | Esc opens it. | The Console can sit under any panel. |
By the end of this lesson you will be able to:
- read the Console: its message levels, its filters, and where each message came from;
- write useful messages with console.log, warn, error, table, group, count and more;
- read an error message in full, and go straight to the line that failed;
- ask the page questions by typing into the Console;
- follow a method for any script problem, from the first red line to the fix.
How to follow this lesson
Press Ctrl + Shift + J to open the Console, then press Run on a block below. Its messages appear in the Console, because a page's frames all write to the same place. Under each block is the list of messages Chrome reported, each with its level, taken from the same stream the panel reads.
In one line
The Console shows what scripts and the browser have to say; you need to know that scripts read the page and that values have types.
The page's diary
At a glance
A ship's captain reads the logbook first when something goes wrong at sea. The Console is a web page's logbook: a DevTools panel that lists messages from the page's scripts and from the browser itself. It opens with Ctrl + Shift + J, or Cmd + Option + J on a Mac.
Each message has a level that says how serious it is: Info, Warning, Error or Verbose. A drop-down and a Filter box cut hundreds of lines down to the few that matter. Preserve log keeps messages across a reload. The rule to remember is short: on any page that misbehaves, read the first red line first.
Take a guess: Which level of message does the Console hide until you ask for it?
A ship keeps a logbook: the time, the weather, each thing that went wrong. When something fails at sea, the captain reads the log first. The Console is a web page's logbook, and it has two uses. It shows messages, and it lets you type code into the running page. This section is about reading.
A DevTools panel that lists messages from the page's scripts and from the browser itself, and has a line at the bottom where you can type JavaScript to run in the page.
Open it with Ctrl + Shift + J, or Cmd + Option + J on a Mac. Run this block with the Console open.
<!DOCTYPE html>
<script>
console.log("Page loaded");
console.info("3 stalls found");
console.warn("Stock is low: rice");
console.error("Could not reach the price list");
console.debug("Width is 800");
</script>
The Console shows
Info Page loaded
Info 3 stalls found
Warning Stock is low: rice
Error Could not reach the price list
Verbose Width is 800
Levels
Each message has a level, which says how serious it is. You will see the first four lines above, and probably not the last.
| Written with | Level | How it looks | Use it for |
|---|---|---|---|
console.log(), console.info() | Info | plain | ordinary notes |
console.warn() | Warning | yellow, with an icon | something odd, but not fatal |
console.error() | Error | red, with an icon | something has failed |
console.debug() | Verbose | hidden unless you ask for it | fine detail you rarely want |
That is why console.debug seemed to do nothing: the Console hides the Verbose level unless you switch it on. It is a common surprise.
Filtering
A real page can log hundreds of lines. Above the messages is a row of tools to cut them down.
| To see | Do this |
|---|---|
| only errors | open the log levels drop-down, and tick only Errors |
| Verbose messages too | tick Verbose in the same drop-down |
| lines holding a word | type the word in the Filter box |
| lines not holding a word | type a minus first, such as -analytics |
| lines from one file | type url: and the file's address |
| only your own messages | open the sidebar, and choose User Messages |
A memory aid
Red first. On any page that misbehaves, filter to Errors and read the first one. Everything else can wait.
Keeping and clearing
| To do this | Do this |
|---|---|
| clear the Console | press Ctrl + L or click the clear button |
| keep messages across a reload | open the Console's settings, and tick Preserve log |
| see every repeat | by default, identical messages are folded into one, with a count beside it |
| see where a message came from | look at the link at the right of the line: a file name and line number |
Preserve log matters when a page reloads or moves on before you can read. A form that submits and goes to a new page takes its messages with it, unless this box is ticked.
Not only your messages
The browser writes to the Console too. When a file is missing, it logs an Error-level message with the address and the status 404. When a page does something unsafe or out of date, it logs a warning. So the Console is useful on pages where you wrote no logging at all, which is why it is the first place to look on any page that misbehaves.
Worked example 1
A news site's page logs dozens of lines, and a reader says the page's search box is broken. Without reading every line, find any errors from the page.
What we have: a page with many messages, and a report of a problem
What we need: only the messages that matter
The plan: use the level filter: errors first
- Press
Ctrl + Shift + Jto open the Console. - Press
Ctrl + Lto clear it, then reload the page, so that only fresh messages show. - Open the log levels drop-down and tick only Errors. Forty lines become two.
- Read the first one. Its link names the file and the line.
<!DOCTYPE html>
<script>
console.log("Ad loaded");
console.log("Fonts ready");
console.warn("Old cookie found");
console.error("search.js could not start");
console.log("Menu ready");
</script>
The Console shows
Info Ad loaded
Info Fonts ready
Warning Old cookie found
Error search.js could not start
Info Menu ready
Filter to Errors, then read the first. Of the five messages here, one matters: search.js could not start.
Check: the check lists all five messages with their levels, and exactly one is at the error level.
When you are stuck: reading the Console
A console.debug line does not appear: tick Verbose in the log levels drop-down.
Messages vanish at a reload: tick Preserve log.
Too many lines: filter to Errors, or hide a noisy word with a minus.
Your turn
Which level is console.warn()?Tap to reveal
- Between Info and Error.
Warning.
Which level is hidden by default?Tap to reveal
- Fine detail.
Verbose.
How do you keep messages when a page reloads?Tap to reveal
- A box to tick.
Tick Preserve log.
Did you know?
The first logs were made of wood
The word log began at sea. In the days of sail, sailors tied a piece of wood, a log, to a rope knotted at regular gaps off the back of the ship. They counted the knots that passed through their hands in a set time to find the ship's speed. That is why speed at sea is still given in knots. A ship's logbook was first a book for writing down those readings.
Why it fits here: This topic calls the Console a page's logbook, and the word log itself began with a piece of wood on a knotted rope.
Sources: Wikipedia: Chip log; Wikipedia: Ship's log; Wiktionary: knot
Message levels from the 1980s
Sorting messages by how serious they are is an old idea. Syslog, a standard for message logging, was developed in the 1980s by Eric Allman as part of the Sendmail project. It became the standard logging solution on Unix-like systems. Its standard of March 2009, RFC 5424, numbers eight severities, from 0, Emergency, "system is unusable", to 7, Debug. Error, Warning, Informational and Debug are among them, close to the console's own error, warn, info and debug.
Why it fits here: The Console's levels are one case of an old habit: grade each message, so that the serious ones can be found first.
Sources: Wikipedia: Syslog; RFC 5424: The Syslog Protocol; Console Standard
In one line
The Console is the page's logbook: each message has a level, Info, Warning, Error or Verbose, and the level drop-down and the Filter box cut it down, so that you can read the first red line first.
Writing in the diary
At a glance
A shopkeeper's rough notebook helps only when it says what was sold, and to whom. Messages in the Console work the same way. The console object has more than log, and each of its methods answers a different question.
Labels make a log readable, and console.table turns a list of objects into a table. Then console.group folds related lines, console.count keeps a tally and console.time measures. The method console.assert speaks only when something is wrong, and console.dir and console.trace show an element's properties and who called. One memory aid holds them all: log what, table many, count how often, time how long, assert only if wrong, trace who called.
Take a guess: If its condition is true, what does console.assert print?
A shopkeeper's rough notebook is most useful when it says more than "sold something". The same goes for the Console: a good message tells you what, and which. The console object has more than log, and each method suits a different question.
console.log: more than one thing
console.log takes as many values as you give it, separated by commas, and it shows arrays and objects in full, so that you can open them.
<!DOCTYPE html>
<script>
const item = "Rice";
const price = 60;
console.log("item", item, "price", price);
console.log([1, 2, 3]);
console.log({ item: "Dal", price: 120 });
</script>
The Console shows
Info item Rice price 60
Info [1, 2, 3]
Info {item: Dal, price: 120}
Label your values
Compare console.log(total) with console.log("total", total). When three numbers appear in a row, the label tells you which is which. In the second form, a shorter way is console.log({ total }), which prints the name and the value together.
console.table: many things, side by side
An array of objects is hard to read as a heap of braces. console.table draws it as a table, with a column for each property, and you can click a heading to sort.
<!DOCTYPE html>
<script>
const cart = [
{ item: "Rice", qty: 2, price: 60 },
{ item: "Dal", qty: 1, price: 120 }
];
console.table(cart);
</script>
The Console shows
Info (a table, one row for each item)
console.group: keeping related lines together
When a step produces several lines, group them. The group can be folded away, and console.groupCollapsed starts it folded.
<!DOCTYPE html>
<script>
console.group("Cart");
console.log("Rice");
console.log("Dal");
console.groupEnd();
console.log("Done");
</script>
The Console shows
Group Cart
Info Rice
Info Dal
Info Done
console.count: how many times?
Does this run once, or twenty times? console.count keeps its own tally, by label. It answers one of the most common questions in debugging, with no counter of your own to write.
<!DOCTYPE html>
<script>
function addToCart() {
console.count("addToCart");
}
addToCart();
addToCart();
addToCart();
</script>
The Console shows
Info addToCart: 1
Info addToCart: 2
Info addToCart: 3
console.time: how long?
Put console.time before a piece of work and console.timeEnd after it, with the same label, to see how many milliseconds it took.
<!DOCTYPE html>
<script>
console.time("sort");
const list = [];
for (let i = 0; i < 1000; i++) list.push(1000 - i);
list.sort();
console.timeEnd("sort");
</script>
The Console shows
Info sort: ... ms
console.assert: speak up only when wrong
console.assert takes a condition and a message, and logs only if the condition is false. You can leave it in place, and it stays silent until something is wrong.
<!DOCTYPE html>
<script>
const price = -5;
console.assert(price > 0, "A price must be above 0");
console.assert(2 + 2 === 4, "This is never shown");
</script>
The Console shows
Error Assertion failed: A price must be above 0
console.dir and console.trace
console.dir shows an element as an object with all its properties, where console.log shows it as a piece of HTML. console.trace prints how the code got here: which function called which.
<!DOCTYPE html>
<script>
function total() {
console.trace("total was called");
}
function checkout() {
total();
}
checkout();
</script>
The Console shows
Info total was called
| Your question | Use |
|---|---|
| what is this value? | console.log("total", total) |
| what is in this list of objects? | console.table(list) |
| how many times does this run? | console.count("name") |
| how long does this take? | console.time("name") and console.timeEnd |
| tell me only if this goes wrong | console.assert(condition, message) |
| who called this? | console.trace() |
| what properties has this element? | console.dir(element) |
A memory aid
log what, table many, count how often, time how long, assert only if wrong, trace who called.
Worked example 2
A cart's total comes out too large. The cart is an array of three objects, and the code adds up each quantity times each price. Choose the best console method to look at the data, and find the bad row.
What we have: an array of three objects, and a total that is too large
What we need: a way to see every row at once
The plan: an array of objects suits console.table; compare each row by eye
- The cart has three rows, so
console.table(cart)lays them out, one row to a line. - In the table, the qty column reads 2, 1 and 20. The last row is the slip: someone typed 20 for 2.
- Fix the data, and the total falls.
<!DOCTYPE html>
<script>
const cart = [
{ item: "Rice", qty: 2, price: 60 },
{ item: "Dal", qty: 1, price: 120 },
{ item: "Tea", qty: 20, price: 15 }
];
console.table(cart);
let total = 0;
for (const row of cart) total += row.qty * row.price;
console.log("total", total);
</script>
The Console shows
Info (a table, one row for each item)
Info total 540
console.table(cart) shows it in one look: 20 teas, not 2. The total of 540 should be 270.
Check: the kit's run logged the table and a total of 540: 120 + 120 + 300.
When you are stuck: writing messages
A message shows only [object Object]: you joined it to text with +; use a comma instead, so that the Console keeps the object.
console.timeEnd shows nothing: its label must match console.time's exactly.
console.assert shows nothing: the condition was true, which is the point.
Your turn
Which method draws an array of objects as a table?Tap to reveal
- It says so.
console.table.
console.assert(1 < 2, "Oops"). What is logged?Tap to reveal
- Is the condition false?
Nothing: it logs only when the condition is false.
How do you find out how many times a function runs?Tap to reveal
- A tally.
Put console.count("name") inside it.
Did you know?
A standard that says please
The console methods have a written standard, the Console Standard, which defines APIs for console debugging facilities. Its status note calls it an early work in progress, and asks readers to be kind and constructive, because it is its editors' first specification. Its entry for console.table asks the browser to build a table, or else fall back to logging the argument. Then it adds a note to itself: "TODO: This will need a good algorithm."
Why it fits here: It shows that standards are written by people, and that console.table, given data it cannot draw as a table, falls back to a plain log.
Source: Console Standard
Messages in colour
A console message can be styled with CSS. The format specifiers of the Console include %s, which formats a value as a string, and %d, which formats it as an integer. One more, %c, "Applies provided CSS". Chrome's documentation shows it at work: console.log("%cHooray", style) prints Hooray in the styles given as the second value, such as a dark blue background with white text.
Why it fits here: A styled label makes your own messages stand out among the hundreds of lines a real page can log.
Sources: Chrome for Developers: Format and style messages in the Console; Console Standard
In one line
Label what you log; console.table shows lists of objects, console.count tallies, console.time measures, console.assert speaks only when something is wrong, and console.trace shows who called.
Reading an error
At a glance
When a car stops, a good mechanic asks what happened, where, and what led to it. A red error line in the Console answers all three, if you read it to the end. Most beginners stop at the word error and start guessing.
An error line has four pieces: Uncaught, the kind of error such as TypeError, the message, and the link to the line. Behind it sits the stack trace, the chain of calls that led to the failure. A handful of errors turn up again and again, and your own code can throw errors on purpose.
Take a guess: Why can one error near the top of a script make a whole page seem dead?
When a car stops, a good mechanic asks three things: what happened, where, and what led to it. A red error line in the Console answers all three, if you read it to the end. Most beginners stop at the word "error" and start guessing.
<!DOCTYPE html>
<script>
const heading = document.querySelector(".title");
heading.textContent = "Fresh bread";
console.log("This line never runs");
</script>
The Console shows
Error Uncaught TypeError: Cannot set properties of null (setting 'textContent')
Run that block. The Console shows one red line:
Uncaught TypeError: Cannot set properties of null (setting 'textContent')
| Piece | What it tells you |
|---|---|
Uncaught | nothing handled this error, so the script stopped here |
TypeError | the kind of problem: a value of the wrong type |
Cannot set properties of null | what happened: something was null when the code used it |
(setting 'textContent') | what the code was trying to do |
| the link at the right | the file and the line; click it to open the Sources panel at that line |
Read it as a sentence: "I tried to set textContent on something, and that something was null." Now the question has changed. It is no longer "why is my page broken?", but "why was heading null?" The answer is that nothing on this page has the class title.
One error, many symptoms
An uncaught error stops the rest of its script. The check above confirms it: the line after the error logged nothing. So one error near the top can make a whole page seem dead. Fix the first red line first; often the others disappear with it.
The stack trace
Click the arrow beside an error to open its stack trace: the chain of function calls that led to the failure, the latest first.
<!DOCTYPE html>
<script>
function readPrice(item) {
return item.price;
}
function addToCart(item) {
return readPrice(item);
}
addToCart(undefined);
</script>
The Console shows
Error Uncaught TypeError: Cannot read properties of undefined (reading 'price')
The trace reads from the top down: the error was in readPrice, which addToCart called, which the page's top level called. Read it upward through your own code, and you find where the bad value came from. Here, the mistake is the undefined passed at the bottom of the script, not the line that failed.
A memory aid
The error shows where it hurts. The stack shows who hit it.
The errors you will meet most
| Message | It means | Look for |
|---|---|---|
Cannot read properties of null | you used something that is not there | a selector that found nothing, or a script that ran too early |
Cannot read properties of undefined | a value was never set | a missing argument, or a misspelt property |
x is not defined | no such name exists (a ReferenceError) | a misspelt variable, or a missing script |
x is not a function | you called something that cannot be called (a TypeError) | a misspelt method, or a wrong value |
Assignment to constant variable | you changed a const (a TypeError) | use let, or a new name |
missing ) after argument list | the code cannot be read at all (a SyntaxError) | a bracket or a quote near that line |
<!DOCTYPE html>
<script>
const total = 100;
console.log("Ready");
console.log(totl);
</script>
The Console shows
Info Ready
Error Uncaught ReferenceError: totl is not defined
A SyntaxError is different from the others. The browser reads the whole script before running it, so one misplaced bracket means no line of that script runs at all, not even the first. If your first console.log does not appear, look for a SyntaxError.
Errors you throw yourself
Your own code can raise an error on purpose, with throw. It stops the script and appears in red, with your words and a stack trace.
<!DOCTYPE html>
<script>
function sell(stock) {
if (stock === 0) {
throw new Error("Stock is empty");
}
}
sell(0);
</script>
The Console shows
Error Uncaught Error: Stock is empty
Worked example 3
A page's script should fill a price, and the Console shows Cannot set properties of null. The selector looks right, and the element is in the HTML. Find out why.
What we have: a null, a good selector, an element that exists
What we need: why the script could not find it
The plan: ask when the script ran: the browser reads from the top, so a script in the head runs before the body exists
- The error says the element was null, so the search found nothing at that moment.
- The script sits in the head. When it runs, the browser has not yet reached the body, so the span does not exist yet.
- Move the script to the end of the body, or add
deferto a script loaded from a file, so that it runs after the page is built.
<!DOCTYPE html>
<head>
<script>
document.querySelector(".price").textContent = "₹60";
</script>
</head>
<body>
<p>Rice: <span class="price"></span></p>
</body>
The Console shows
Error Uncaught TypeError: Cannot set properties of null (setting 'textContent')
<!DOCTYPE html>
<body>
<p>Rice: <span class="price"></span></p>
<script>
document.querySelector(".price").textContent = "₹60";
</script>
</body>
Checked in Chrome
- with the script after the element, the price is filled, and there is no error
The script ran before the element existed. Put it at the end of the body.
Check: the first version raised the error, and the second filled the price.
Worked example 4
The Console says totl is not defined. The word total appears all over the script. What do you do?
What we have: a ReferenceError, with a name that is nearly right
What we need: the slip, and how to find it fast
The plan: read the name in the message letter by letter; a name that nearly matches is a typing slip
- The message quotes the exact name it could not find:
totl. - Click the link at the right of the line. It opens the script at that line, and the slip is there.
- Correct the name.
<!DOCTYPE html>
<script>
const total = 100;
console.log(total);
</script>
The Console shows
Info 100
A typing slip: totl for total. The message quoted the very word.
Check: with the name corrected, the script logged 100 and raised no error.
When you are stuck: reading errors
Many red lines: fix the first one; the others are often its results.
Nothing at all in the Console, and nothing works: is there a SyntaxError, or is the script file missing? Check Network.
The error points into a library's file: open the stack trace, and find the first line that is in your own code.
Your turn
What does Uncaught mean in a red line?Tap to reveal
- Nothing handled it.
No code handled the error, so the script stopped there.
Which part of an error shows who called the function that failed?Tap to reveal
- Open the arrow.
The stack trace.
document.querySelector(".x") finds nothing. What does it give?Tap to reveal
- It is not undefined.
null.
Did you know?
Ten frames, and why
In Chrome, an error's stack property normally holds at most ten calls. V8, the JavaScript engine used in Chrome and in Node.js, gives almost every error a stack property holding the topmost 10 stack frames. Its makers chose 10 because it is usually enough to be useful without a noticeable cost in speed. Setting Error.stackTraceLimit changes the number, and Infinity collects every frame. The stack property itself is not standardized: MDN marks it Non-standard.
Why it fits here: It explains why a very long chain of calls can be cut short in a stack trace, and how to collect all of it.
Sources: V8; V8: Stack trace API; MDN: Error.prototype.stack
TypeError, the catch-all
TypeError turns up for many different slips, and the JavaScript standard says why. It uses TypeError for an unsuccessful operation when none of the other error types fits the cause. MDN lists such cases. One is a value of a type that the operation does not expect. Another is a change to a value that cannot be changed, and a third, a value used in a way that does not suit it. EvalError has the opposite fate. The standard does not use it at all now, and keeps it only for compatibility with earlier editions.
Why it fits here: Most red lines in this topic's table are TypeErrors, and this is the reason: the standard makes TypeError the error for anything without a better name.
In one line
An error names its kind, says what happened and links to the line; the stack trace shows how the code got there. Read the whole line, and fix the first red line first, because an uncaught error stops the script.
Asking the page questions
At a glance
So far the Console has talked to you, but it also listens. At the bottom is a prompt, a small arrow, and whatever you type there runs in the page, with everything the page knows. It is like leaning in to ask a running machine what is in one of its wheels right now.
The Console adds its own short helpers: $0 for the element you picked, $ and $$ for one match or all of them, and copy to take a value away. Live Expressions keep a value on show as it changes. A drop-down at the top chooses which frame, a page inside the page, you are talking to.
Take a guess: Can a script in your own file use the Console's $0 helper?
So far the Console has been talking to you. It also listens. At the bottom is a prompt, a small >, and whatever you type there runs in the page, with everything the page knows. It is like being able to lean in and ask a running machine: "What is in that wheel right now?"
Run the block below, and type each of these in the Console, pressing Enter after each. The Console prints the answer on the next line.
<!DOCTYPE html>
<ul>
<li class="price">₹60</li>
<li class="price">₹120</li>
<li class="price">₹45</li>
</ul>
<footer>
<a href="#help">Help</a>
<a href="#terms">Terms</a>
</footer>
Checked in Chrome
- document.querySelectorAll("li").length answers 3
- document.querySelector("li").textContent answers "₹60"
- and 2 + 3 answers 5: the Console is a calculator too
| To do this | Do this |
|---|---|
| run what you typed | press Enter |
| add another line first | press Shift + Enter |
| bring back an earlier line | press the Up arrow key |
| finish a word | press Tab to accept the suggestion |
| see the answer before running | read the grey preview under the line, which is Eager Evaluation |
You can change the page as well. Type document.querySelector("li").textContent = "₹55", and the first price changes on the page. As with everything in DevTools, a reload puts it back.
The Console's own helpers
The Console adds a few short names that are worth learning. They exist only here, so never put them in a script.
| Helper | Means | Example |
|---|---|---|
$0 | the node selected in the Elements panel | $0.textContent |
$_ | the last answer | $_ + 1 |
$("sel") | the first match, like document.querySelector | $("h1") |
$$("sel") | all matches, as a real array | $$("a").length |
copy(value) | copies a value to the clipboard | copy($$("a").length) |
clear() | clears the Console | |
getEventListeners(node) | lists the events a node is listening for | getEventListeners($0) |
monitorEvents(node, "click") | logs each such event as it happens | monitorEvents($0, "click") |
inspect(node) | selects a node in the Elements panel | inspect($("h1")) |
A memory aid
One dollar, one element. Two dollars, all of them. And $0 is the one you picked.
<!DOCTYPE html>
<h1>Asha Stores</h1>
<script>
console.log($0);
</script>
The Console shows
Error Uncaught ReferenceError: $0 is not defined
That block fails on purpose: a script cannot use the Console's helpers. Forgetting this, and pasting a line you tried in the Console into your file, is a common slip.
Live Expressions: a value that keeps updating
Suppose you want to watch which element has focus as you press Tab. Typing the question each time would be slow. Click the eye icon at the top of the Console, and type document.activeElement. The value is pinned above the messages and updates by itself. Any question you keep asking can go there.
Which page are you talking to?
A page can hold frames, and each frame is a page of its own. The blocks in these lessons run inside frames. Near the top of the Console is a drop-down that normally says top, the main page. Code you type runs in the chosen one. To ask a block's page a question, Run it, open the drop-down, and choose its frame. If the Console says that something is null when you can see it on the screen, the wrong page is selected.
Worked example 5
A shop asks how many prices are on its page, and wants them in a list for a spreadsheet. Get the answer from the Console, without writing a file.
What we have: a page with prices that share a class
What we need: a count, and a list of text you can paste
The plan: $$ gives a real array of matches, so .length counts them, and .map turns each element into its text
- Count them:
$$(".price").length. - List them:
$$(".price").map(e => e.textContent). The Console prints the array. - Copy it:
copy($_)copies the last answer. Paste it wherever it is needed.
<!DOCTYPE html>
<ul>
<li class="price">₹60</li>
<li class="price">₹120</li>
<li class="price">₹45</li>
</ul>
<footer>
<a href="#help">Help</a>
<a href="#terms">Terms</a>
</footer>
Checked in Chrome
- the count is 3
- and the list is ₹60, ₹120 and ₹45
$$(".price").length gives 3, and $$(".price").map(e => e.textContent) gives the list.
Check: the check ran the same search with its plain equivalent, and got the same answers.
When you are stuck: typing in the Console
null for something you can see: check the drop-down at the top: are you in the right frame?
Pressing Enter runs the line too soon: press Shift + Enter to add a line.
$0 is undefined in the Console: nothing is selected yet; click a node in the Elements panel first.
Your turn
What does $$("a") give?Tap to reveal
- Two dollars.
All the links, as an array.
Can a script in your file use $0?Tap to reveal
- They exist only in one place.
No: the helpers exist only in the Console.
How do you add a second line without running the first?Tap to reveal
- Enter with something else.
Shift + Enter.
Did you know?
Type allow pasting
The Console is powerful enough to be dangerous. In an attack called Self-XSS, attackers trick people into pasting harmful code into DevTools, which can hand over their web accounts and personal information. So since Chrome 120, a new DevTools user who tries to paste into the Console sees a warning, and must type allow pasting first. Once pasting has been allowed once, the warning never shows again.
Why it fits here: It is the safety rule of this topic: paste into the Console only code that you understand and have read yourself.
Source: Chrome for Developers: What's new in DevTools (Chrome 120)
Five picks remembered
The Console remembers more than your last pick. The names $0, $1, $2, $3 and $4 refer to the last five elements you inspected in the Elements panel, with $0 the most recent. The $ helper also gives way to the page. If the page uses a library such as jQuery that defines its own $, the library's $ is the one you get.
Why it fits here: It saves typing: inspect a few elements in turn, then compare them in the Console as $0 to $4.
Source: Chrome for Developers: Console Utilities API reference
In one line
Type at the Console's prompt to ask the page anything; $0, $, $$ and copy are helpers that exist only there, Live Expressions keep a value on show, and the drop-down at the top chooses which frame you are talking to.
From the first red line to the fix
At a glance
Problems in scripts come in two kinds. Some shout, with a red line in the Console. Others are silent: no error at all, and the wrong result. A good method handles both, the way a doctor's routine works for any patient.
Make the problem happen on purpose, clear the Console and reload, and read the first red line. With no red line, log what you expect at each stage until the first surprise, halving the chain each time. Change one thing at a time, and remove your logs at the end.
Take a guess: How many logs, at most, can find one bad step in a chain of a thousand lines?
Problems in scripts come in two kinds. Some shout: there is a red line. Others are silent: no error at all, and the wrong result. The method handles both.
| Step | Do this | Why |
|---|---|---|
| 1 | Make it happen, on purpose | a problem you can repeat is a problem you can solve |
| 2 | Open the Console, clear it, reload | so that you see only fresh messages |
| 3 | Is there a red line? Read the first | it names the kind, the place, and what it was doing |
| 4 | Click its link | it opens the very line |
| 5 | No red line? Log what you expect at each stage | you are looking for the first place where the truth differs from your belief |
| 6 | Change one thing, and test | two changes at once hide which one worked |
| 7 | Remove your logs | the page's Console should stay clean |
Step 5 is the heart of it. A script is a chain of steps. Somewhere, a value stops being what you think it is. Put a log in the middle of the chain. If the value is right there, the fault is later; if wrong, earlier. Halve the chain again. Ten logs at most will find any bad step in a thousand lines.
A memory aid
Expect, then look. Before each log, say what you expect it to print. The first surprise is your bug.
Worked example 6
A cart shows "Total: ₹NaN". There is no red line. Find the cause with logs.
What we have: a silent problem: a wrong result, and no error
What we need: the first value that is not what you expect
The plan: log each value before it is used, and say what you expect it to be
- Expect the price to be a number. Log it:
console.log("price", price, typeof price). It prints text, ₹60. - There is the surprise. The script read the price from the page, and page text is text. Multiplying ₹60 by 2 gives
NaN, which means "not a number". - Take the number out of the text before using it:
Number(price.slice(1)).
<!DOCTYPE html>
<p class="price">₹60</p>
<script>
const price = document.querySelector(".price").textContent;
console.log("price", price, typeof price);
const total = price * 2;
console.log("total", total);
</script>
The Console shows
Info price ₹60 string
Info total NaN
<!DOCTYPE html>
<p class="price">₹60</p>
<script>
const price = Number(document.querySelector(".price").textContent.slice(1));
console.log("price", price, typeof price);
const total = price * 2;
console.log("total", total);
</script>
The Console shows
Info price 60 number
Info total 120
The price was text. Number(price.slice(1)) gives 60, and the total is 120.
Check: the logs read string and NaN before the fix, and number and 120 after it.
Worked example 7
A "Buy" button does nothing, and the Console is empty. The click handler looks fine. Find out why.
What we have: a silent problem: no error, and nothing happens
What we need: whether the handler was ever attached
The plan: log at each stage: how many buttons did the script find? Does a click reach the handler?
- Expect one button. Log it:
console.log("found", buttons.length). It prints 0. - That explains the silence.
querySelectorAllfound nothing, and a loop over nothing runs no times, so no handler was attached and nothing failed. - Compare the selector and the HTML: the script says
.buy, and the button hasclass="buy-now".
<!DOCTYPE html>
<button class="buy-now">Buy</button>
<script>
const buttons = document.querySelectorAll(".buy");
console.log("found", buttons.length);
buttons.forEach(function (b) {
b.addEventListener("click", function () { console.log("clicked"); });
});
</script>
The Console shows
Info found 0
<!DOCTYPE html>
<button class="buy-now">Buy</button>
<script>
const buttons = document.querySelectorAll(".buy-now");
console.log("found", buttons.length);
buttons.forEach(function (b) {
b.addEventListener("click", function () { console.log("clicked"); });
});
</script>
Checked in Chrome
- a click now reaches the handler
The Console shows
Info found 1
Info clicked
The selector found nothing. A loop over nothing fails silently. Use .buy-now.
Check: the first run logged found 0; the second logged found 1, then clicked.
When you are stuck: script problems
No error and no result: log at the first step, and work forward.
It worked yesterday: what changed? Undo changes one at a time.
A fix that seems to do nothing: are you editing the file the page loads? Add a log at the top of the file, and see if it appears.
Your turn
You see three red lines. Which do you read first?Tap to reveal
- The later ones may be its results.
The first.
What does NaN mean?Tap to reveal
- Three words.
Not a number: a sum with something that is not a number.
querySelectorAll finds nothing, and a loop runs over it. What error appears?Tap to reveal
- An empty list is a fine list.
None: the loop runs no times.
Did you know?
A log that changes after the fact
A logged object can mislead. MDN warns that information about an object is lazily retrieved: the Console shows its contents as they are when you first open it, not as they were when it was logged. DevTools marks such a value with a small note, whose source code reads: This value was evaluated upon first expanding. It may have changed since then. MDN's cure is to log a deep copy.
Why it fits here: It matters for this topic's method: when you log what you expect at each stage, log a copy, or the log may show a later value.
Sources: MDN: console; Chrome DevTools frontend source: ConsoleViewMessage.ts
Bugs that hide when watched
Sometimes looking at a bug changes it. A heisenbug is a bug that seems to disappear or change when you try to study it. The name is a pun on Werner Heisenberg, the physicist who first introduced the uncertainty principle. Adding output statements can alter a program in subtle ways, such as the timing of its run. The earliest known use of the word is from 1983, in an ACM publication.
Why it fits here: It explains a strange moment in debugging: a bug that hides as soon as you add a log to look for it.
Sources: Wikipedia: Heisenbug; Wiktionary: heisenbug
In one line
Make the problem happen, clear the Console and read the first red line; with no red line, log what you expect at each stage until something surprises you, and change one thing at a time.
Where it is used
The Console is the first thing a working developer opens when a report says "it does not work".
| What you learned | Where it is used | A real example |
|---|---|---|
| filtering to Errors | any page reported as broken | finding why the payment step fails on one browser |
| console.table | looking at data | reading fifty orders that came back from a server |
| console.count | things that run too often | finding that a handler fires twice for one click |
| console.time | rough timing | comparing two ways of sorting a long list |
| reading a stack trace | large programs | tracing a crash through a framework into your own code |
| $$ and copy | quick jobs on any page | pulling all the links from a page into a list |
| Live Expressions | watching a value change | seeing which element has focus while testing the keyboard |
| Preserve log | pages that move on | reading an error that flashes past as a form submits |
Mistakes and debugging
These are the Console slips everyone makes, measured in the browser where they can be.
1. Not reading the message
The word "error" is not the message. The fix: read the whole line as a sentence, then click its link.
2. Starting from the last red line
The last error is usually a result of an earlier one. The fix: scroll up to the first.
3. Joining an object to text with +
<!DOCTYPE html>
<script>
const cart = { item: "Rice" };
console.log("cart: " + cart);
console.log("cart:", cart);
</script>
The Console shows
Info cart: [object Object]
Info cart: {item: Rice}
The plus turns the object into the useless text [object Object]. The fix: use a comma, and the Console keeps the object.
4. Trusting an opened object
The Console shows an object as it is when you open the arrow, not as it was when it was logged. If the code changed it afterwards, you will see the later values, and the small i beside it warns you. The fix: log a copy, with JSON.stringify(value), to freeze that moment.
5. A filter left on
You typed a word in the Filter box yesterday, or unticked Errors, and today the Console is suspiciously calm. The fix: look at the Filter box and the level drop-down, which should say Default levels, before you believe that all is well.
6. The wrong frame
Your question runs in top, and the thing you want is in a frame. The fix: choose the frame in the drop-down.
7. Leaving logs in
Dozens of old messages hide the one you need, and may show private data to anyone who opens the Console. The fix: remove them when the bug is fixed.
8. Using alert to debug
alert() stops the page, must be dismissed each time, and shows objects badly. The fix: console.log, or, in a later lesson, a breakpoint.
The debugging corner: the Console beside anything
Press Esc in any panel to open the Drawer with the Console in it. Now you can pick an element in the Elements panel and question it as $0 in the same view, or read messages while you watch the Network panel.
Quick card
The lesson on one card.
Every kind of message in the lesson
<!DOCTYPE html>
<p class="price">₹60</p>
<script>
const cart = [{ item: "Rice", qty: 2 }, { item: "Dal", qty: 1 }];
console.group("Cart");
console.table(cart);
console.groupEnd();
console.count("load");
console.warn("Stock is low");
console.assert(cart.length > 5, "Fewer than 6 items");
const price = document.querySelector(".price").textContent;
console.log("price", price, typeof price);
document.querySelector(".nope").textContent = "x";
console.log("never reached");
</script>
The Console shows
Group Cart
Info (a table, one row for each item)
Info load: 1
Warning Stock is low
Error Assertion failed: Fewer than 6 items
Info price ₹60 string
Error Uncaught TypeError: Cannot set properties of null (setting 'textContent')
| To do this | Do this |
|---|---|
| open the Console | Ctrl + Shift + J, or Esc for the Drawer |
| clear it | Ctrl + L |
| see only errors | the level drop-down, Errors |
| see console.debug | the level drop-down, Verbose |
| hide a word | type -word in the Filter box |
| keep messages over a reload | Preserve log |
| a value, with its name | console.log("total", total) |
| a list of objects | console.table(list) |
| a tally | console.count("name") |
| a timing | console.time("name"), console.timeEnd("name") |
| only if wrong | console.assert(condition, message) |
| the selected node | $0 |
| first match, all matches | $("sel"), $$("sel") |
| a line with no run | Shift + Enter |
| a value always on show | the eye icon, Live Expressions |
And the rule of the second glass: the first red line first, read to the end.
The story: The first red line
You read the red line slowly. It names the machine's complaint, and the exact place in the script where it stopped. The script had tried to fill the list before the list had been built, and everything after that line never ran.
You move one line, and the timetable fills from top to bottom. To be sure, you ask the machine a question through the glass, and it answers at once.
"You read it to the end," Ottilie says, "and you read the first red line first. Most people start with the last one."
Reagents gathered: Console, console.log, TypeError, stack trace, $0, Live Expression.
Sources
- Chrome DevTools documentation (Page content CC BY 4.0, code samples Apache 2.0 (the footer of its pages, read 2026-11-06); reused with credit)
- 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)