Console Methods — Debugging

The console object prints to the Console panel in DevTools (the browser's built-in developer tools), and it has a tool for each need. log prints one line per…

You add console.log in five places, refresh, and the Console is full of numbers. Which number came from which function? Which line is an error and which is just info? They all look the same.

The trouble is that most people only know console.log. console has many more tools. console is the browser's built-in object that prints to the Console panel. That panel is part of DevTools, the set of tools for developers that is built into the browser. If console.log is one pen, console is a whole box of writing tools:

They all print to the Console panel, just like console.log, but the result is far easier to read.

console.log: one call, one line

const data = [45, 23, 67, 12, 89, 34, 56, 78, 90, 11];

console.log(data.length);               // 10
console.log("min:", 11, "max:", 90);    // min: 11 max: 90
console.log("min:" + 11 + ",max:" + 90); // min:11,max:90

warn and error: give it a level

console.warn("Only 3 numbers, the average doesn't say much");
console.error("The data is empty, there's nothing to count");

console.warn prints in yellow with a triangle icon. console.error prints in red, and also shows a stack trace: the chain of functions that were called to reach that line. The colour marks the line's level: a warning or an error. Levels help because the Console panel has a Default levels menu that filters lines by level. Pick Errors only, and hundreds of plain logs disappear from view.

console.table: an array of objects becomes a table

console.table([
  { name: "Ana", age: 25 },
  { name: "Budi", age: 30 }
]);
(index) name age
0 'Ana' 25
1 'Budi' 30

The columns come from the property names: name and age. There is also an (index) column, which holds the position in the array. Ana and Budi don't become columns. They are the contents, so they go into rows. For an array of objects, for example data you got from a server through an API, this table is far easier to read. Compare it with console.log, which only shows (2) [{…}, {…}].

console.group: group lines together

console.group("analyzeArray");
console.log(10);
console.log("min:11,max:90");
console.log(50.5);
console.groupEnd();

The Console shows the title analyzeArray with a small triangle, and the three lines under it are indented. Click the triangle to fold those three lines. console.groupCollapsed works the same way, but the group starts folded. Every group needs a groupEnd. Without it, every later log is indented too.

time and count: measure and count

console.time("loop");
let sum = 0;
for (let i = 0; i < 10000; i++) sum += i;
console.timeEnd("loop"); // loop: 0.52 ms (the number differs every run)

console.count("click"); // click: 1
console.count("click"); // click: 2

If you need the duration as a number (not just text in the Console), record the time yourself. Date.now() gives the current time in milliseconds. Call Date.now() before and after the code you measure, then subtract:

const start = Date.now();
for (let i = 0; i < 10000; i++) sum += i;
const duration = Date.now() - start;
console.log("time:" + duration + "ms"); // time:0ms

Date.now() counts only whole milliseconds, so a loop this short usually records 0. performance.now() is more precise: its result has decimals. So round it first with Math.round when you need a whole number.

The exercise: summarising an array of numbers

In the exercise, you summarise the data above. This is what you calculate:

What How Result
number of items arr.length 10
smallest Math.min(...arr) 11
largest Math.max(...arr) 90
average total 505 divided by 10 50.5

Inside the exercise's function, that array is called arr. The calculation looks like this:

const count = arr.length;
const min = Math.min(...arr);
const max = Math.max(...arr);
const total = arr.reduce((acc, n) => acc + n, 0);
const avg = Math.round((total / count) * 100) / 100;

Three more: assert, dir, trace

⚠️ Small slips that change the output

TL;DR: The console object prints to the Console panel in DevTools (the browser's built-in developer tools), and it has a tool for each need. log prints one line per call. warn and error print in yellow and red, and you can filter them with the Console's Default levels menu. table turns an array of objects into a table, with an (index) column plus the property names, such as name and age. group/groupEnd groups lines, time/timeEnd is a stopwatch (the labels must match), and count counts calls. assert only prints when the condition is false, and dir shows every property and method of a DOM element. trace prints the chain of functions that were called to reach the trace line. For a duration as a number, call Date.now() before and after the code you measure, then subtract. To round an average x to two decimal places and keep it a number (not text), use Math.round(x * 100) / 100.

⚡ One call, one line

Write:

console.log("min:", 11, "max:", 90);    // min: 11 max: 90
console.log("min:" + 11 + ",max:" + 90); // min:11,max:90

Meaning: Each console.log prints exactly one line in the Console panel. Values separated by commas are printed with spaces between them. When the format has to be exact, with no spaces, join the parts into one text yourself with +.

⚡ An array of objects becomes a table

Write:

console.table([
  { name: "Ana", age: 25 },
  { name: "Budi", age: 30 }
]);
Guess first: console.table prints this array as a table. Which columns does the table have?

(index), name and age. The columns come from the property names, plus an (index) column for the position in the array. Ana and Budi are the contents, so they go into rows.

Meaning: For an array of objects, for example data from a server, console.table is far easier to read than console.log.

⚡ Give it a level, group it, time it

Meaning: console.warn prints a yellow line with the level warning, and console.error prints a red line with the level error. The Default levels menu in the Console panel can filter lines by level, for example to show only errors. The lines between console.group and console.groupEnd are grouped together and indented. console.time("loop") starts a stopwatch, then console.timeEnd("loop") prints how many milliseconds the code between them took. The labels have to match exactly.

⚡ The average stays a number

Write:

const avg = Math.round((total / count) * 100) / 100;
Guess first: toFixed(2) also writes a number with 2 decimal places. What does (50.5).toFixed(2) give?

The text "50.50", not a number. When the number 50.5 is what's asked for, use Math.round(x * 100) / 100, where x is the average.

Meaning: total holds the sum of all the numbers, and count holds how many numbers there are. This line rounds the average to 2 decimal places, and the result stays a number.

What you will learn