Skip to content
aviral gupta

// B1.4 · ~30 min · Beginner

The console and the debugger

After this lesson you can pick the right console method for a message, find a logic error by logging labelled values, and pause a program with debugger or node inspect to look at its values.

Lesson 4 of 5 in B1 Getting started

You will be able to

  • Choose console.log, info, warn, error or table and say whether it writes to stdout or stderr
  • Find a logic error by logging labelled values step by step
  • Pause a program with a debugger statement, in the browser DevTools and with node inspect
  1. Warm-up · Activity 1 of 7

    Warm-up: in Node.js, which of these print to stderr instead of stdout? Pick all that apply.

    Select all that apply.

  2. Predict · Activity 2 of 7

    Predict before you read on. The total should be 24, but the program prints total: 14. What does the first console.log print?

    const price = 4;
    const count = 3;
    const subtotal = price + count;
    console.log("subtotal:", subtotal);
    const total = subtotal * 2;
    console.log("total:", total);
  3. Practice · Activity 3 of 7

    Fill in the method so that the list is drawn as a table, with an (index) column and a Values column.

    console.____(["tea", "coffee"]);
    console.(["tea", "coffee"]);
  4. Practice · Activity 4 of 7

    Match each piece of code to what it does in Node.js.

  5. Practice · Activity 5 of 7

    A program prints a wrong total and no error. Put the steps of a logging hunt in order.

    1. 1.Run again and find the first value that is wrong
    2. 2.Run once more, then remove the extra logs
    3. 3.Run the program and note the wrong result
    4. 4.Log the value of each step with a label
    5. 5.Fix the line that computes that value
  6. Brain teaser · Activity 6 of 7

    Brain teaser. You run this with node main.js, with no debugger attached. What does it print before it stops?

    console.log("start");
    debugger;
    console.log("x is", x);
    console.log("end");
  7. Apply · Activity 7 of 7

    Mini-task. This program should print the pay after 10% tax for 6 hours at 12 an hour (64.8), but it prints something else: const hours = 6; const rate = 12; const pay = hours + rate; const tax = pay / 10; console.log("after tax:", pay - tax);. Add a labelled console.log after each step, find the first wrong value, fix that line, and run it again.

    Check your work against this list

Build it yourself

Read the worked example, then write the exercises. Your code runs in your browser or on your computer and is never uploaded.

Worked example

A café bill, traced

The café bill again, now with a console method for each job. console.info announces the bill, console.table shows the order as rows and columns, labelled console.log lines trace each step of the sum, and console.warn reports a problem on stderr, so it is not in the output below. The order is a list of records: {item: "coffee", …} is an object, which module B5 covers; here it is only printed.

main.js

// A café bill, with each step traced.
const items = [
  {item: "coffee", price: 3.2, count: 2},
  {item: "cake", price: 4.5, count: 1}
];
console.info("Bill for table", 4);
console.table(items);
const coffees = 3.2 * 2;
console.log("coffees:", coffees);
const total = coffees + 4.5;
console.log("total:", total);
console.warn("(printer: paper low)");

Run it with

node main.js

Output

Bill for table 4
┌─────────┬──────────┬───────┬───────┐
│ (index) │ item     │ price │ count │
├─────────┼──────────┼───────┼───────┤
│ 0       │ 'coffee' │ 3.2   │ 2     │
│ 1       │ 'cake'   │ 4.5   │ 1     │
└─────────┴──────────┴───────┴───────┘
coffees: 6.4
total: 10.9
  • console.info prints like console.log, to stdout.
  • console.table makes one row per item and one column per field, plus the (index) column.
  • The labels coffees: and total: tell you which step each number comes from.
  • console.warn goes to stderr: a terminal shows it, but it is not part of the output above.
Change it and run it

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads the JavaScript runner (up to 0.1 MB) and keeps it cached. Your code runs in your browser’s own engine and stays on your device.

Exercises

Exercise 1 of 2

Each message on its stream

The program prints four messages, all with console.log. Keep all four messages, but change the methods: Loading the menu is information (console.info), Tea is sold out is a warning (console.warn), Menu items: 3 is the result (console.log), and Printer not found is an error (console.error). Then only the first and the third line are left on stdout.

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads the JavaScript runner (up to 0.1 MB) and keeps it cached. Your code runs in your browser’s own engine and stays on your device.

Hints
  1. Hint 1

    Only the method name changes: console.log("Tea is sold out") becomes console.warn("Tea is sold out").

  2. Hint 2

    console.info prints to stdout, like console.log; console.warn and console.error print to stderr.

  3. Hint 3

    Do not delete any message: the warning and the error still appear in the terminal, just on stderr.

Show a solution

One way to solve it. Yours can look different and still pass the checks.

console.info("Loading the menu");
console.warn("Tea is sold out");
console.log("Menu items:", 3);
console.error("Printer not found");
Run it on your computer

Install ECMAScript 2026 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.

main.js

console.log("Loading the menu");
console.log("Tea is sold out");
console.log("Menu items:", 3);
console.log("Printer not found");

main.test.js

import {test} from 'node:test';
import assert from 'node:assert/strict';
import {runMain} from './learnrun.js';

const lines = async () => (await runMain()).trimEnd().split('\n');

test('prints the information and the result on stdout', async () => {
  const got = await lines();
  assert.deepEqual(got, ['Loading the menu', 'Menu items: 3'], `stdout was ${JSON.stringify(got)}`);
});

test('keeps the warning off stdout', async () => {
  const got = await lines();
  assert.ok(!got.includes('Tea is sold out'), 'Tea is sold out is still on stdout: use console.warn');
});

test('keeps the error off stdout', async () => {
  const got = await lines();
  assert.ok(!got.includes('Printer not found'), 'Printer not found is still on stdout: use console.error');
});

package.json

{
  "type": "module"
}

package.json tells Node.js that the .js files are modules; keep it in the folder.

Run the program:

node main.js

Run the checks (needs learnrun.js in the same folder):

node --test
Download learnrun.js

Exercise 2 of 2

Trace the average

The average of 70, 80 and 90 should be 80, but the program prints Average: 180, with no error. Store the sum of the three scores in its own constant sum and log it with the label Sum:, so the program first prints Sum: 240. Then compute the average from sum and print Average: 80.

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads the JavaScript runner (up to 0.1 MB) and keeps it cached. Your code runs in your browser’s own engine and stays on your device.

Hints
  1. Hint 1

    Split the long line in two: const sum = first + second + third; then console.log("Sum:", sum);.

  2. Hint 2

    Once Sum: 240 is right, the bug is in the division: in first + second + third / 3, only third is divided.

  3. Hint 3

    const average = sum / 3; divides the whole sum.

Show a solution

One way to solve it. Yours can look different and still pass the checks.

const first = 70;
const second = 80;
const third = 90;
const sum = first + second + third;
console.log("Sum:", sum);
const average = sum / 3;
console.log("Average:", average);
Run it on your computer

Install ECMAScript 2026 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.

main.js

const first = 70;
const second = 80;
const third = 90;
const average = first + second + third / 3;
console.log("Average:", average);

main.test.js

import {test} from 'node:test';
import assert from 'node:assert/strict';
import {runMain} from './learnrun.js';

const lines = async () => (await runMain()).trimEnd().split('\n');

test('logs the sum first, with its label', async () => {
  const got = await lines();
  assert.equal(got[0], 'Sum: 240', `the first line is ${JSON.stringify(got[0])}, expected "Sum: 240"`);
});

test('prints the right average', async () => {
  const got = await lines();
  assert.equal(got[1], 'Average: 80', `the second line is ${JSON.stringify(got[1])}, expected "Average: 80"`);
});

test('prints exactly two lines', async () => {
  const got = await lines();
  assert.equal(got.length, 2, `the program printed ${got.length} line(s), expected 2`);
});

package.json

{
  "type": "module"
}

package.json tells Node.js that the .js files are modules; keep it in the folder.

Run the program:

node main.js

Run the checks (needs learnrun.js in the same folder):

node --test
Download learnrun.js

Common mistakes

A typo in a console method

const items = ["tea", "coffee"];
console.tabel(items);

What Node.js prints

TypeError: console.tabel is not a function

Why, and the fix

console exists, but it has no method called tabel, and calling something that is not a function is a TypeError. Check the spelling of the method: console.table. The same goes for console.lg, console.eror and friends.

Logging a name that does not exist

const subtotal = 5;
console.log("subtotal:", subtotl);

What Node.js prints

ReferenceError: subtotl is not defined

Why, and the fix

A log line is code too: the name you log must be spelled exactly as it was declared. Here the label is right, but the value is a misspelled name. Copy the name from its const or let line.

Calling debugger like a function

console.log("start");
debugger();
console.log("end");

What Node.js prints

SyntaxError: Unexpected token '('

Why, and the fix

debugger is a statement, like const, not a function: write debugger; on its own. Because this is a SyntaxError, the file cannot be read and not even start is printed.

JavaScript in the browser: your browser’s own engine, in a sandboxed worker. Syntax errors are located with acorn 8.18.0, MIT. Licence and source

Exit ticket

5 questions, no hints. Score 80% or more to complete the lesson.

Finish every activity above to unlock the exit ticket.

Report a problem

Spotted something wrong or unclear? Say what, and it will be checked and fixed.

#

At least 20 characters.

Only if you want a reply.

Key ideas

Five console methods, two streams

console.log prints to stdout, the program’s normal output. In Node.js, console.info and console.debug are aliases for console.log, and console.warn is an alias for console.error: those two print to stderr, the channel for messages about the program rather than its results. A browser console shows them all in one list, styled by level, and lets you filter by level. console.table(list) draws an array as rows and columns, with an (index) column; for a list of records, each field becomes a column. The checks on this page read stdout only.

Log labelled values to find a logic error

A logic error gives no message, only a wrong result. To find it, print the value after each step with a label, such as console.log("subtotal:", subtotal), run again, and compare every line with what you worked out by hand. The first line that disagrees points to the code just above it. Labels matter: a column of bare numbers is hard to match to the code. Fix that line and run again. Then delete the extra logs, or keep them for later, as MDN’s troubleshooting guide suggests.

Pause instead of print: debugger

The statement debugger; asks a debugger to pause there. With the browser DevTools open, the page stops at that line, like at a breakpoint, and you can read the value of each variable before you go on. With no debugger attached, as with plain node main.js or the editor on this page, debugger; does nothing. In a terminal, node inspect main.js starts Node’s own debugger: it stops at the first line that runs, cont (c) runs on to the next breakpoint, next (n) runs one more line, and p total prints the value of total.

Sources

Last reviewed September 30, 2026