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:
- yellow and red highlighters:
warnanderror, - a ruler for drawing tables:
table, - folders for grouping sheets of paper:
group, - a stopwatch:
time, - a tally counter (press it once and the number goes up by one):
count.
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
- Each
console.logcall prints exactly one line. In the exercise, the checker reads line 0, line 1, line 2, so the order of the calls matters. - Several values separated by commas are printed with spaces between them.
- When the format has to be exact, such as
min:11,max:90with no spaces, join the parts into one text yourself with+.
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
console.time("loop")starts a stopwatch calledloop.console.timeEnd("loop")stops it, then prints how long it took in milliseconds. The labels have to match exactly.console.count("click")prints how many times that label has been counted. Useful for finding out how often a function is called.
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;
...arr(spread) pours the array out as separate arguments. You need it becauseMath.mintakes numbers, not an array.Math.round(x * 100) / 100rounds x to 2 decimal places, and the result stays a number. Fordata, the average prints as50.5, not the text"50.50".
Three more: assert, dir, trace
console.assert(condition, message)only prints when the condition is false.console.assert(15 >= 18, "Not old enough")printsAssertion failed: Not old enough. A true condition prints nothing.console.dir(element)shows a DOM element as a JavaScript object, with all its properties and methods (classList,children,textContent...).console.log(element)shows it as HTML. Usedirwhen you want to see what's inside the object.console.trace("who?")prints the chain of functions that called that line.
⚠️ Small slips that change the output
- A format that's slightly off.
console.log("min:", 11)printsmin: 11, with a space. Ifmin:11,max:90is what's asked for, join it into one text. toFixed(2)for the average.(50.5).toFixed(2)gives the text"50.50". If the number50.5is what's asked for, useMath.round(x * 100) / 100.- A different
timelabel.console.time("loop")thenconsole.timeEnd("Loop")don't match, because upper and lower case count. - Forgetting to clean up. Debugging logs that you leave in the code reach your users too. Remove them before the code is deployed (put on a server so people can use it).
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.