Topic 0.3
The Console and DevTools
In one line
The console is where your program talks back to you: console.log and its relatives print values, you can type and run JavaScript there directly, and every error shows up with its type, message and the line that caused it.
Think of it like this
A car's dashboard. While you drive, you can't see the engine, but the dashboard shows the speed, the fuel and a warning light when something is wrong. The console is your program's dashboard: you can't see variables inside the running code, so you print them, and the console shows red warning lights (errors) with a note saying exactly where the problem is.
Words you'll meet
New words in this topic, in plain English. Come back here whenever one feels fuzzy.
- Console
- The DevTools panel (and Hectal's panel under each example) where your code prints messages and errors appear.
- console.log
- The command that prints values to the console.
- Warning
- A yellow console message: something looks wrong, but the code keeps running.
- Error
- A problem the engine can't continue past. Unhandled ones appear in red, starting with
Uncaught. - REPL
- Read, Evaluate, Print, Loop: a prompt where you type code, it runs, and you see the result at once.
- Stack trace
- The list under an error showing which function called which, down to the line that failed.
- Breakpoint
- A marker on a line in the Sources panel that pauses the code there so you can look at the values.
Step by step
01Open the console
Press F12 and click Console, or press Ctrl+Shift+J (Cmd+Option+J on a Mac). Click the 🚫 icon (Clear console) or press Ctrl+L to clear old messages.
02Run code at the prompt
Type an expression and press Enter. The console prints its value. If a line has no value (like declaring a variable), it prints undefined; that's normal, not an error.
03Print from your program
In your code, label what you print. A bare 120 in a busy console is hard to place; Total: 120 isn't.
const total = 40 * 3;
console.log("Total:", total);
if (total > 100) {
console.warn("Big order:", total);
}04Read an error
Here the id is wrong, so getElementById returns null. The console shows the type, the message and the place.
Read it like a sentence: "A TypeError happened: I couldn't set textContent on null, at line 2 of app.js." So the question is: why was it null? Answer: no element has the id titel.
const heading = document.getElementById("titel");
heading.textContent = "Hi";05Pause the code instead of guessing
In Sources, click a line number to set a breakpoint, then reload. The code stops on that line, and you can hover over variables to see their values and step forward one line at a time. Writing debugger; in your code does the same while DevTools is open.
Try it yourself
- 1
Fix the error
In the third example, predict what the console shows once you correct
titeltotitle. Fix it and run: all three steps print and the heading changes. - 2
Use your browser's console
Open DevTools on this page, type
document.titleand press Enter. Then try[1, 2, 3].lengthand"hello".toUpperCase(). Predict each answer before pressing Enter. - 3
Make three kinds of error on purpose
In your browser's console, type each line and read the type of error:
alert(,prnt("hi")andnull.length. Which is a SyntaxError, which a ReferenceError and which a TypeError?
Code & diagrams
Strings inside lists and objects are shown in single quotes, so you can tell the text `42` from the number 42.
Preview
Console
Nothing logged yet.Expected console output
Hello, console!
Several values: 42 true null
A list: [ 'tea', 'coffee' ]
An object: { name: 'Asha', age: 12 }
Info: the page loaded
Warning: stock is low
Error: payment failedTry this in your browser's own console: the same array becomes a neat table with an (index) column.
Preview
Console
Nothing logged yet.Expected console output
[ { name: 'Asha', score: 91 }, { name: 'Ravi', score: 78 }, { name: 'Meera', score: 85 } ]
Players: 3Steps 1 and 2 ran, then the error stopped the script. The log on step 2 shows the cause: the heading is `null` because of the typo `titel`.
Preview
Console
Nothing logged yet.Expected console output
Step 1: starting
Step 2: heading is null
Uncaught TypeError: Cannot set properties of null (setting 'textContent')Break it on purpose
Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.
Break #1
Call something that isn't a function
Write console.log = "hi"; and then console.log("test");.
Break #2
Print an object and change it later
In the browser's DevTools, run const o = { n: 1 }; console.log(o); o.n = 2;, then expand the logged object.
Myth vs fact
Myth
Errors in the console mean the whole page is broken.
Fact
An error stops one script at that point. Other scripts, the HTML and the CSS keep working. Read the error to see which part failed.
Myth
console.log slows down or breaks production sites.
Fact
A few logs cost almost nothing. But logging huge objects in loops can slow things down and keeps them in memory, and logs can leak private data, so build tools often remove them for production.
Myth
undefined after typing a line in the console is an error.
Fact
It's the value of the statement you typed. Declarations like const x = 1 have no value, so the console shows undefined.
Pro corner
Extra depth for experienced readers. New to this? Skip it for now and come back later.
- ▸
More console tools in DevTools:
console.group()/groupEnd()(indent related logs),console.time("label")/timeEnd("label")(measure time),console.count("label")(count calls),console.assert(cond, msg)(log only when a condition is false),console.trace()(print the call stack) andconsole.dir(el)(show an element as an object instead of HTML). - ▸
DevTools console helpers that only exist at the prompt:
$0(the element selected in Elements),$_(the last result),$("sel")and$$("sel")(query shortcuts),copy(value)(copy to the clipboard). The prompt also allows top-levelawaitand lets you redeclarelet/constnames, which normal scripts don't. - ▸
Error text differs between engines. Chrome says
Cannot read properties of null (reading 'x'); Firefox saysTypeError: el is null; Safari saysnull is not an object (evaluating 'el.x'). Learn to read the type and the location, which are always there. - ▸
Live expressions (the eye icon in the Console) re-evaluate an expression continually, handy for watching
document.activeElementwhile tabbing through a form. Logpoints (right-click a line number in Sources) add a log without editing the code.
Remember this
- 1
DevTools are the developer tools built into every browser. Open them with
F12orCtrl+Shift+J(Cmd+Option+Jon a Mac) to jump straight to the Console panel. On Hectal, every live example has its own console under the preview, which prints values the same way. - 2
console.log(value)prints a value. Give it several values separated by commas and it prints them on one line with spaces between:console.log("Total:", 120)printsTotal: 120. It's the tool you'll use most: when code misbehaves, log the values and compare them with what you expected. - 3
There are levels for different kinds of message.
console.infoandconsole.debugare for information;console.warnshows a yellow warning (something odd, but the program carries on);console.errorshows a red error message. DevTools lets you filter by level, so using the right one keeps a busy console readable.console.table(array)draws an array of objects as a table in DevTools (Hectal's console prints it on one line). - 4
The console is also a place to run code. Type
2 + 2and press Enter: it prints4. This is called a REPL (Read, Evaluate, Print, Loop): it reads what you type, runs it, prints the result, and waits for more. It runs inside the current page, sodocument.titleshows that page's title. PressShift+Enterfor a new line without running, and the Up arrow to bring back earlier commands. - 5
When something goes wrong, the engine throws an error, and if nothing handles it you see it in red, starting with
Uncaught. Read it in three parts: the type (TypeError,ReferenceError,SyntaxError,RangeError), the message (what went wrong, such asCannot read properties of null (reading 'textContent')), and the location on the right (app.js:12, the file and line). Click the location to jump to that line in the Sources panel. - 6
The common types tell you where to look. SyntaxError: the grammar is wrong (a missing bracket), and nothing in that script ran. ReferenceError: you used a name that doesn't exist, often a typo or wrong capital letter. TypeError: the value exists but is the wrong kind for what you did, such as calling something that isn't a function or reading a property of
nullorundefined. RangeError: a number is outside the allowed range. The script stops at the error; lines before it have already run.
Explain it without notes
How do you read a console error message? Use an example.
What is the difference between a SyntaxError, a ReferenceError and a TypeError?
When would you use console.warn or console.error instead of console.log?
Why can logging an object in DevTools show different values when you expand it?
Practice
Write code that stores a price of 250 and a discount of 50, then logs Price after discount: 200, and logs a warning Discount is more than 10% because it is.
This code throws. Say which error type and why, then fix it: const list = document.querySelector("#items"); list.append("tea"); on a page with <ul id="item"></ul>.
Trade-offs
- ↔
Logging is quick and works everywhere, but you must guess where to log and clean up after; breakpoints show every value at once without editing code, but need DevTools open and take a little practice.
Done when you can
I can open the console and run code at the prompt.
I can print labelled values with
console.log,warnanderror.I can use
console.tablefor a list of objects.I can read an error's type, message and line number.
I can tell a SyntaxError, a ReferenceError and a TypeError apart.
I can set a breakpoint in the Sources panel.