Sub topic 4
Using the Console
This chapter assumes you know basic JavaScript syntax, can open DevTools (covered earlier), and have selected elements in the Elements panel. The Console is where you read messages from your page and run JavaScript against it.
What the Console does
The Console has two jobs. It shows messages that the page, the browser and your code produce. It also gives you a prompt where you type JavaScript and see the result at once. Code you type runs in the context of the current page, so it can read and change the live DOM and any global variables.
Logging with severity levels
The console object has several methods. Each one marks a message with a severity, and DevTools styles and filters messages by that severity.
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();console.logprints general information.console.warnprints a yellow warning.console.errorprints a red error and a stack trace, which lists the chain of function calls that led to it.console.tableshows an array of objects as a table with one row per item.console.groupandconsole.groupEndindent the messages between them under a collapsible heading.
Use the level selector and the filter box in the Console toolbar to hide noise. For example, show only errors, or type a word to see only messages containing it.
Console Utilities
Console Utilities are helpers that exist only in the Console prompt. They are not part of your page, so do not use them in your source files.
// 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 gives you |
|---|---|
| `$0` | The element currently selected in the Elements panel |
| `$_` | The result of the last expression you ran |
| `$(selector)` | The first match, like `document.querySelector` |
| `$$(selector)` | All matches, as a real array |
| `copy(value)` | Copies a value to the clipboard |
The link to the Elements panel is the useful part. Select a suspicious element, then test ideas on $0 in the Console before you edit any source code.
Evaluating expressions
You can type any expression and press Enter. Press Shift+Enter to add a new line without running the code. DevTools also shows a preview of the result as you type, and the up arrow recalls earlier commands.
A typical session when a button seems not to respond:
- Select the button in the Elements panel.
- Type
$0.disabledin the Console. If it returnstrue, the page has disabled the button. - Type
$0.disabled = falseand click the button to test whether the handler works. - Type
getEventListeners($0)to list the handlers attached to it. This utility is also Console-only.
Changes you make this way last only until the page reloads. Treat the Console as a place to test a hypothesis, then make the real fix in your code.
Common errors
- Uncaught errors from the page. A red
Uncaught TypeErrormessage includes a link to the file and line. Click the link to open that line in the Sources panel, where you can set a breakpoint. $0 is not definedor anullresult. You have not selected an element in the Elements panel, or you selected it in a different frame. Select the element again.- Using utilities in source code. Writing
$$('img')in your script works only if you defined$$yourself. It fails with aReferenceErrorin normal page code. - Messages you expected are missing. Check the level filter, the filter text and the "Preserve log" setting. Without Preserve log, navigating to another page clears the Console.
- Excess logging in production. Remove debug
console.logcalls before you ship. They slow hot code paths slightly and can expose internal data to anyone who opens DevTools.
One caution about objects: the Console shows the object's state when you expand it, not when you logged it. If the code changes the object afterward, the expanded view can show newer values. To capture a snapshot, log a copy, such as console.log(structuredClone(obj)).
From the Console to the debugger
The Console tells you that something went wrong. To find out why, you usually need to pause the code. A debugger statement pauses execution at that line when DevTools is open. The next chapter covers breakpoints and stepping in detail.
function applyDiscount(price, percent) {
const discount = price * percent / 100;
debugger; // execution pauses here when DevTools is open
return price - discount;
}
applyDiscount(80, 25);When the code pauses, switch to the Console. It now runs in the scope of the paused function, so you can type discount and see 20.
Exercise
You select a <ul> in the Elements panel. Which Console expression returns how many <li> children it directly contains, and why can you not use this expression inside your site's own script file?
Show answer
$0.children.length returns the count of child elements. $0 is a Console Utility that exists only in the DevTools Console prompt, so in a script file it is undefined and would throw a ReferenceError. In page code you would use something like document.querySelector('ul').children.length.
Exercise
You call console.log(settings) with an object, then your code changes settings.theme. When you expand the logged object later, it shows the new theme. How do you record the value as it was at the moment of logging?
Show answer
Log a copy of the object, for example console.log(structuredClone(settings)). The Console reads an object's properties when you expand it, so logging the original reference can show later changes.