Sub topic 4
Using the Console
The Console is the panel where you run JavaScript against the live page and read what the page reports about itself. This chapter covers log levels and formatting, filtering, the Console Utilities, evaluating code in context, and the errors you will meet most often.
This chapter assumes you can open DevTools and select an element in the Elements panel, as covered in the earlier chapters. It also assumes you know basic JavaScript syntax, including functions, arrays and objects. Panel names follow Chromium-based browsers. Firefox and Safari have a Console with the same core features.
What the Console does
The Console has two jobs:
- It is an output channel. Your code, the browser and any third-party scripts write messages to it. Failed requests, security warnings and uncaught exceptions appear there too.
- It is a REPL (read-eval-print loop). You type an expression, the browser evaluates it in the page's context, and the result is printed.
The Console runs code in the same JavaScript environment as the page. A global variable you can see in the Console is the same variable your page scripts use. This is why it is useful for debugging, and why you should be careful about what you paste into it from other people.
Open the Console with F12 or Ctrl+Shift+J (Cmd+Option+J on macOS). You can also press Esc while in another panel to open the Console drawer at the bottom. The drawer lets you keep the Console visible while you work in Elements or Sources.
Severity levels and formatting
The console object has several methods that differ in severity. The browser styles each one differently and lets you filter by level.
console.log('plain message');
console.warn('something looks off');
console.error('something failed');
console.table([
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Grace' }
]);
console.group('Request details');
console.log('method: GET');
console.log('status: 200');
console.groupEnd();| Method | Level shown | Typical use |
|---|---|---|
| `console.log` | Info | General output |
| `console.info` | Info | Same display as `log` in Chromium |
| `console.warn` | Warning | Recoverable problems, deprecated usage |
| `console.error` | Error | Failures. Includes a stack trace in Chromium |
| `console.debug` | Verbose | Detail that is hidden unless you enable Verbose |
| `console.table` | Info | Arrays or objects displayed as rows and columns |
| `console.group` / `groupEnd` | Info | Indented, collapsible sets of messages |
Choose the level that matches the meaning of the message. A later filter on "Errors" is only useful if you reserved console.error for real errors.
Logging objects
When you log an object, the Console shows a live reference, not a copy. If the object changes after the log call, expanding it later shows the current values, not the values at the time of logging. This is a common source of confusion.
const state = { count: 0 };
console.log(state); // expand later: may show count: 5
state.count = 5;
console.log(JSON.stringify(state)); // a string snapshot: {"count":5}
console.log({ ...state }); // a shallow copy taken nowIf you need the value at a specific moment, log a snapshot such as a JSON.stringify string or a copy. Note that JSON.stringify drops functions and undefined values, and it throws on circular references.
Format specifiers and styling
The first argument to a logging method can contain format specifiers:
%sformats a string.%dor%iformats an integer.%fformats a float.%oformats an expandable DOM-aware object.%Oformats an expandable JavaScript object.%capplies CSS to the text that follows.
console.log('User %s has %d unread messages', 'Ada', 3);
console.log('%cBuild OK', 'color: green; font-weight: bold');console.table also accepts a second argument listing the columns to show, which helps with wide objects:
console.table(
[{ id: 1, name: 'Ada', role: 'admin' }, { id: 2, name: 'Grace', role: 'user' }],
['id', 'name']
);Counting, timing and assertions
A few other methods remove the need for ad hoc variables:
console.count('label')prints how many times that line has run with that label.console.countReset('label')resets it.console.time('label')starts a timer andconsole.timeEnd('label')prints the elapsed time.console.assert(condition, message)prints an error only when the condition is false.console.trace()prints the call stack at that point, which shows who called the current function.
function handleClick() {
console.count('handleClick calls');
console.assert(document.querySelector('#save'), 'Save button is missing');
}Filtering and reducing noise
Real pages produce a lot of output. The Console toolbar has several controls for narrowing it.
- Log level dropdown: show or hide Verbose, Info, Warnings and Errors.
- Filter box: type text to show matching messages. Prefix with
-to exclude, for example-analytics. A regular expression between slashes such as/error \d+/also works. - Context selector: switch between the top page and iframes, workers or extensions.
- Hide network messages: removes routine request logs, so that only failures remain.
- Preserve log: keeps messages when the page navigates or reloads. Without it, the Console clears on each navigation. Turn it on when debugging something that happens during a redirect or form submit.
- Group similar: collapses repeated messages into one entry with a count.
Two details are worth knowing. First, console.clear() is ignored for the "Preserve log" setting in some versions, so if messages seem to persist, check that checkbox. Second, a message from a script shows the file and line number on its right. Click it to open the source in the Sources panel. This link may point at minified code unless a source map is loaded.
Console Utilities
The Console provides helper functions and variables that exist only in the Console. They are not available to your page scripts, so do not put them in application code.
// Run in the Console after selecting an element in the Elements panel.
$0.classList.toggle('hidden'); // $0 is the currently selected element
$$('img').length; // $$ is shorthand for document.querySelectorAll, returned as an array
copy($0.outerHTML); // copy() puts a value on the clipboard| Utility | What it does |
|---|---|
| `$0` to `$4` | The most recently selected elements in the Elements panel. `$0` is the latest. |
| `$_` | The value of the last expression evaluated. |
| `$(selector)` | Shorthand for `document.querySelector`. Returns the first match. |
| `$$(selector)` | Shorthand for `document.querySelectorAll`, returned as a real array. |
| `$x(path)` | Evaluates an XPath expression and returns an array of matches. |
| `copy(value)` | Copies a string representation of the value to the clipboard. |
| `keys(obj)` / `values(obj)` | The keys or values of an object as an array. |
| `inspect(obj)` | Opens the element in Elements or the object in the relevant panel. |
| `monitor(fn)` / `unmonitor(fn)` | Logs each call to a function with its arguments. |
| `monitorEvents(el, 'click')` | Logs events of that type on an element. Stop with `unmonitorEvents`. |
| `getEventListeners(el)` | Returns the listeners registered on an element. |
| `debug(fn)` / `undebug(fn)` | Sets a breakpoint that pauses when the function is called. |
| `clear()` | Clears the Console. |
If your page defines its own $ (for example jQuery), the page's definition takes precedence in the global scope. In that case $ in the Console is jQuery, not the utility. $$, $0 and the others usually still work.
A short session shows how these combine:
// 1. Find images missing alt text and list their sources
$$('img:not([alt])').map(img => img.src);
// 2. Watch which clicks reach a button
monitorEvents($('#save'), 'click');
// 3. See what handlers are attached
getEventListeners($('#save'));Use $$ with array methods directly. This is more convenient than document.querySelectorAll, which returns a NodeList with fewer methods.
Evaluating code in context
Live expressions
Click the eye icon in the Console toolbar to create a live expression. The expression is re-evaluated about every 250 ms and its value is shown above the prompt. This is useful for watching window.scrollY, document.activeElement or a counter in your app while you interact with the page. Live expressions have a small cost, so remove them when you are done.
Eager evaluation
As you type an expression, Chromium shows a grey preview of the result below the prompt. It evaluates only expressions that have no side effects, so array.map(...) previews, while counter++ does not run until you press Enter. Do not rely on the preview for code that changes state.
Scope and the paused state
Outside a pause, the Console evaluates code in the global scope. Variables declared with let or const inside a function or module are not reachable. When execution is paused at a breakpoint or debugger statement, the Console evaluates in the scope of the paused frame, so local variables are available.
function applyDiscount(price, percent) {
const discount = price * percent / 100;
debugger; // execution pauses here when DevTools is open
return price - discount;
}
applyDiscount(80, 25);While paused on the debugger line, type discount in the Console and it returns 20. You can also test a fix: evaluate price - discount * 2 to see what a changed formula returns, without editing the file. The debugger statement does nothing when DevTools is closed, but you should remove it before shipping.
Top-level await and promises
The Console supports await at the top level. This lets you try asynchronous code directly:
const res = await fetch('/api/items');
const items = await res.json();
items.length;If you omit await, the Console shows a Promise in a pending or fulfilled state instead of the value. That is expected: the result is the promise object itself.
Re-declaration and the last result
In Chromium, you may re-declare a let or const variable in the Console without a SyntaxError. This differs from a regular script, where re-declaration is an error. The relaxation exists so you can retry a statement while experimenting. Remember it when you copy Console code into a file: it may fail there.
Reading errors
The Console lists errors with a message, a source location and, for exceptions, a stack trace. Each frame in the stack is a function call. The top frame is where the error occurred, and the frames below are its callers. Click the arrow to expand the stack.
| Message | Likely cause | First thing to check |
|---|---|---|
| `Uncaught TypeError: Cannot read properties of undefined (reading 'x')` | You accessed a property on `undefined`. An earlier value was missing. | Which variable is `undefined`? Log it before the failing line. |
| `Uncaught ReferenceError: foo is not defined` | The name does not exist in scope. A script may have failed to load or run in the wrong order. | Script order and the Network panel for a failed script request. |
| `Uncaught SyntaxError: Unexpected token '<'` | The browser expected JavaScript but received HTML, often an error page. | The Network panel: open the script request and read the response. |
| `Failed to load resource: the server responded with a status of 404` | A requested URL does not exist. | The URL in the Network panel. |
| `Access to fetch at ... has been blocked by CORS policy` | The server did not send the headers that permit cross-origin access. | The response headers in the Network panel. Fix on the server, not in the page. |
| `Mixed Content` warning | An HTTPS page asked for an HTTP resource. | Change the URL to HTTPS. |
| `Uncaught (in promise) ...` | A rejected promise had no `catch` handler. | Add `.catch` or `try/catch` around `await`. |
Note that the Console message for a CORS failure is deliberately vague about the cause. The browser hides details of the blocked response from scripts. Use the Network panel to see the actual headers.
Pause on exceptions
The Console tells you an error happened, but not always why. In the Sources panel you can enable "Pause on exceptions" so that execution stops at the throw. Then you can use the Console in that frame to inspect values. This pairing is the standard route from a Console error to a diagnosis. The next chapter covers it in detail.
Common mistakes
- Leaving
console.login production code. Logs can leak data such as tokens or personal information, and they add noise. Strip them in your build or use a logger with levels. - Logging an object and trusting its later expansion. As shown earlier, it reflects the current state. Log a copy for a snapshot.
- Assuming the Console shows the page's top scope while inside an iframe. Check the context selector.
- Pasting unknown code. A script pasted into the Console runs with the full privileges of the page, including access to cookies not marked
HttpOnlyand to local storage. Only run code you understand. Browsers print a warning for this reason. - Using Console Utilities in application code.
$0,copyandgetEventListenersdo not exist outside the Console, so a page script that uses them throws aReferenceError.
A short debugging workflow
- Open the Console and reload with "Preserve log" on if the problem happens at load.
- Filter to Errors and read the first error. Later errors are often side effects of the first.
- Click the source link to jump to the line, then add a breakpoint or a
debuggerstatement. - When paused, evaluate variables and candidate fixes in the Console.
- Confirm the fix by repeating the action and checking that the error is gone.
Exercise
A page logs console.log(user) early in a script, and later code sets user.name = 'Grace'. When you expand the logged object in the Console after the page finishes loading, name shows 'Grace', but you need to know its value at the time of the log call. What change to the logging line gives you that, and what is one limitation of the approach you chose?
Show answer
Log a snapshot instead of the live reference, for example console.log(JSON.stringify(user)) or console.log({ ...user }). The Console shows live objects, so expanding later reflects current values. JSON.stringify drops functions and undefined values and throws on circular references. A spread copy is shallow, so nested objects are still live references.
Exercise
You have selected a button in the Elements panel. Write a Console expression that lists every event listener attached to it, and name the utility that would log each click on it as it happens.
Show answer
getEventListeners($0) returns the registered listeners for the selected element, because $0 refers to the current selection. monitorEvents($0, 'click') logs each click event until unmonitorEvents($0) is called.
Exercise
The Console reports Uncaught SyntaxError: Unexpected token '<' for app.js. Which panel do you open next, and what do you expect to find?
Show answer
Open the Network panel and select the app.js request. The < suggests the response is HTML, such as a 404 or login page returned instead of JavaScript, so check the status code, the response body and the requested URL.