JavaScript Console Methods and Debugging Basics (log, table, time, assert and more)
console.log() is the first tool every JavaScript developer and tester learns, but the console can do much more: print tables of test data, time how long a step takes, count calls, group related output and warn only when a check fails. In this lesson you will learn every console method worth knowing, how output goes to stdout and stderr, and how to pause a program with breakpoints and the debugger statement.
π What You’ll Learn: console.log, info, warn and error, format specifiers, console.table, console.group, console.time, console.count, console.assert, console.dir and console.trace, stdout versus stderr, the debugger statement, breakpoints in VS Code and node inspect.
π’ console.log, info, warn and error
Definition: the console object gives you methods to print messages. In Node.js they go to the terminal; in a browser they go to the DevTools Console.
π levels.js
console.log("Test suite started");
console.info("Base URL:", "https://sqatools.in");
console.warn("Retrying login, attempt", 2);
console.error("Login failed: status", 401);
β¨οΈ Terminal
node levels.js
π₯οΈ Output
Test suite started
Base URL: https://sqatools.in
Retrying login, attempt 2
Login failed: status 401
- Pass several values separated by commas; the console prints them with a space between.
console.infois the same asconsole.log.console.warnandconsole.errorwrite to stderr (the error stream) instead of stdout. In the browser they appear in yellow and red and can be filtered by level.
π‘ Tip: CI systems and shells can separate the two streams. node levels.js 2> errors.log sends only the warning and the error to errors.log, while the normal logs still appear in the terminal.
π§Ύ Printing Objects, Arrays and Formatted Text
The console formats objects and arrays so you can read them, which makes it ideal for checking API responses and test data.
π objects.js
const user = { id: 7, name: "Asha", roles: ["tester", "admin"], active: true };
const scores = [91, 78, 85];
console.log(user);
console.log("Scores:", scores);
console.log(`User ${user.name} has ${scores.length} scores`);
β¨οΈ Terminal
node objects.js
π₯οΈ Output
{ id: 7, name: 'Asha', roles: [ 'tester', 'admin' ], active: true }
Scores: [ 91, 78, 85 ]
User Asha has 3 scores
Format specifiers are placeholders in the first argument that are replaced by the following arguments:
| Specifier | Inserts |
|---|---|
%s | A string |
%d or %i | An integer |
%f | A floating-point number |
%o / %O | An object (detailed / plain) |
%j | JSON (Node.js only) |
%c | CSS styles (browser only; ignored in Node.js) |
π format.js
console.log("%s passed %d of %d tests", "Asha", 18, 20);
console.log("Pass rate: %f%%", 90.5);
console.log("Payload: %j", { email: "qa@sqatools.in" });
β¨οΈ Terminal
node format.js
π₯οΈ Output
Asha passed 18 of 20 tests
Pass rate: 90.5%
Payload: {"email":"qa@sqatools.in"}
%% prints a literal percent sign. Template literals (`...${value}`) are usually easier to read, so use specifiers mainly when you see them in other people’s code.
π console.table: Show Data as a Table
console.table() prints an array of objects (or an object) as a table. It is perfect for test data and API results.
π table.js
const results = [
{ test: "login", status: "passed", ms: 812 },
{ test: "search", status: "failed", ms: 1530 },
{ test: "checkout", status: "passed", ms: 2104 },
];
console.table(results);
console.table(results, ["test", "status"]); // only these columns
β¨οΈ Terminal
node table.js
π₯οΈ Output
βββββββββββ¬βββββββββββββ¬βββββββββββ¬βββββββ
β (index) β test β status β ms β
βββββββββββΌβββββββββββββΌβββββββββββΌβββββββ€
β 0 β 'login' β 'passed' β 812 β
β 1 β 'search' β 'failed' β 1530 β
β 2 β 'checkout' β 'passed' β 2104 β
βββββββββββ΄βββββββββββββ΄βββββββββββ΄βββββββ
βββββββββββ¬βββββββββββββ¬βββββββββββ
β (index) β test β status β
βββββββββββΌβββββββββββββΌβββββββββββ€
β 0 β 'login' β 'passed' β
β 1 β 'search' β 'failed' β
β 2 β 'checkout' β 'passed' β
βββββββββββ΄βββββββββββββ΄βββββββββββ
The (index) column shows the array position. The second argument limits which columns are printed.
ποΈ console.group: Indent Related Output
console.group(label) starts an indented section and console.groupEnd() closes it. Groups can be nested.
π group.js
console.group("Checkout flow");
console.log("Add item to cart");
console.group("Payment");
console.log("Enter card details");
console.log("Confirm order");
console.groupEnd();
console.log("Show confirmation page");
console.groupEnd();
console.log("Flow finished");
β¨οΈ Terminal
node group.js
π₯οΈ Output
Checkout flow
Add item to cart
Payment
Enter card details
Confirm order
Show confirmation page
Flow finished
In the browser, console.groupCollapsed() creates a group that starts closed, which keeps long logs tidy.
β±οΈ console.time and console.count
console.time(label) starts a timer and console.timeEnd(label) stops it and prints the elapsed time. console.timeLog(label) prints the time so far without stopping.
π timer.js
console.time("build report");
let total = 0;
for (let i = 0; i < 1_000_000; i++) {
total += i;
}
console.timeLog("build report", "loop done");
const report = JSON.stringify({ total });
console.timeEnd("build report");
console.log(report);
β¨οΈ Terminal
node timer.js
π₯οΈ Output
build report: 2.44ms loop done
build report: 4.052ms
{"total":499999500000}
Your times will differ; they depend on your computer. Use labels so you can run several timers at once.
console.count(label) prints how many times it has been called with that label. console.countReset(label) sets it back to zero.
π count.js
function retry(action) {
console.count(`retry ${action}`);
}
retry("login");
retry("login");
retry("upload");
retry("login");
console.countReset("retry login");
retry("login");
β¨οΈ Terminal
node count.js
π₯οΈ Output
retry login: 1
retry login: 2
retry upload: 1
retry login: 3
retry login: 1
β console.assert: Log Only When a Check Fails
console.assert(condition, ...message) prints Assertion failed with your message only when the condition is false. Unlike node:assert, it does not stop the program.
π assert.js
const statusCode = 500;
const items = ["pen", "book"];
console.assert(items.length === 2, "Expected 2 items");
console.assert(statusCode === 200, "Expected status 200 but got", statusCode);
console.log("The program keeps running after a failed console.assert");
β¨οΈ Terminal
node assert.js
π₯οΈ Output
Assertion failed: Expected status 200 but got 500
The program keeps running after a failed console.assert
β οΈ Watch out: console.assert is for quick debugging only. A test must fail when a check fails, so in tests use node:assert, expect() from Jest or Vitest, or Playwright’s expect(), which throw an error and mark the test as failed.
π¬ console.dir and console.trace
console.log stops showing nested objects after 2 levels and prints [Object] instead. console.dir(obj, { depth: null }) prints every level.
π dir.js
const response = {
status: 200,
body: { user: { profile: { address: { city: "Pune" } } } },
};
console.log(response);
console.dir(response, { depth: null });
β¨οΈ Terminal
node dir.js
π₯οΈ Output
{ status: 200, body: { user: { profile: [Object] } } }
{
status: 200,
body: {
user: { profile: { address: { city: 'Pune' } } }
}
}
console.trace() prints a message plus the call stack: the chain of function calls that led to this line. It answers “who called this function?”.
π trace.js
function saveOrder() {
console.trace("saveOrder was called");
}
function checkout() {
saveOrder();
}
checkout();
β¨οΈ Terminal
node trace.js
π₯οΈ Output
Trace: saveOrder was called
at saveOrder (/home/you/js-course/trace.js:2:11)
at checkout (/home/you/js-course/trace.js:5:3)
at Object.<anonymous> (/home/you/js-course/trace.js:7:1)
Read the stack from the top: saveOrder was called by checkout (line 5), which was called from the top of the file (line 7).
π Debugging Basics: Breakpoints and the debugger Statement
Logging is quick, but a debugger lets you pause a running program, inspect every variable and step through it line by line.
Breakpoints in VS Code
- Open the file and click in the gutter left of a line number. A red dot (the breakpoint) appears.
- Press F5 and choose Node.js. The program stops at the breakpoint, before running that line.
- Hover over a variable, or look in the Variables panel, to see its value.
- Use the toolbar: Continue (F5), Step Over (F10), Step Into (F11) and Step Out (Shift+F11).
The debugger statement
Writing debugger; in your code acts like a breakpoint, but only when a debugger is attached (VS Code with F5, Chrome DevTools open, or node inspect). Without a debugger it does nothing, which the next run proves:
π debug.js
function calculateTotal(prices) {
let total = 0;
for (const price of prices) {
debugger; // pauses here only when a debugger is attached
total += price;
}
return total;
}
console.log("Total:", calculateTotal([10, 20, 30]));
β¨οΈ Terminal
node debug.js
π₯οΈ Output
Total: 60
To use the built-in terminal debugger, run node inspect debug.js. Type cont to run to the next debugger statement, repl to inspect variables, and .exit to quit. Chrome can also attach to node --inspect-brk debug.js from chrome://inspect.
π‘ Tip: Remove debugger; statements and noisy console.log calls before you commit code. ESLint’s no-debugger and no-console rules can remind you.
π Console Method Cheat Sheet
| Method | Use it to |
|---|---|
console.log / info | Print general messages and values |
console.warn / error | Print warnings and errors (to stderr) |
console.table | Show arrays of objects as a table |
console.group / groupEnd | Indent related messages |
console.time / timeLog / timeEnd | Measure how long code takes |
console.count / countReset | Count how often a line runs |
console.assert | Print a message only when a condition is false |
console.dir | Print deep objects with { depth: null } |
console.trace | Print the call stack |
console.clear | Clear the console (browser and terminal) |
π Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Print Order 1042 shipped to Pune twice: once with a template literal and once with format specifiers.
Show answer
π practice1.js
const id = 1042;
const city = "Pune";
console.log(`Order ${id} shipped to ${city}`);
console.log("Order %d shipped to %s", id, city);π₯οΈ Output
Order 1042 shipped to Pune
Order 1042 shipped to PuneQ2. Show this data as a table with only the name and price columns.
const products = [
{ name: "Pen", price: 10, stock: 120 },
{ name: "Notebook", price: 45, stock: 30 },
];Show answer
π practice2.js
const products = [
{ name: "Pen", price: 10, stock: 120 },
{ name: "Notebook", price: 45, stock: 30 },
];
console.table(products, ["name", "price"]);π₯οΈ Output
βββββββββββ¬βββββββββββββ¬ββββββββ
β (index) β name β price β
βββββββββββΌβββββββββββββΌββββββββ€
β 0 β 'Pen' β 10 β
β 1 β 'Notebook' β 45 β
βββββββββββ΄βββββββββββββ΄ββββββββQ3. Measure how long it takes to build an array of 100,000 numbers, using a timer labelled fill.
Show answer
π practice3.js
console.time("fill");
const numbers = [];
for (let i = 0; i < 100_000; i++) {
numbers.push(i);
}
console.timeEnd("fill");
console.log("Length:", numbers.length);π₯οΈ Output
fill: 3.88ms
Length: 100000The time printed will be different on your computer.
Q4. Use console.assert to print a message only if a password is shorter than 8 characters. Test it with "secret".
Show answer
π practice4.js
const password = "secret";
console.assert(password.length >= 8, "Password too short:", password.length, "characters");π₯οΈ Output
Assertion failed: Password too short: 6 charactersThe condition describes what should be true. Because 6 >= 8 is false, the message is printed.
Q5. Count how many times clickButton() is called with each button name, for the calls "save", "cancel", "save".
Show answer
π practice5.js
function clickButton(name) {
console.count(name);
}
clickButton("save");
clickButton("cancel");
clickButton("save");π₯οΈ Output
save: 1
cancel: 1
save: 2Q6. console.log(config) prints [Object] for a nested value. Print the whole object instead.
const config = { env: { qa: { db: { host: "qa-db", port: 5432 } } } };Show answer
π practice6.js
const config = { env: { qa: { db: { host: "qa-db", port: 5432 } } } };
console.dir(config, { depth: null });π₯οΈ Output
{
env: { qa: { db: { host: 'qa-db', port: 5432 } } }
}You can also use console.log(JSON.stringify(config, null, 2)) to print it as indented JSON.
π§ MCQ Quiz: Console Methods and Debugging Basics
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- Where does
console.error()write its output in Node.js?Answer: stderr (the error stream).console.warnandconsole.erroruse stderr;logandinfouse stdout. - Which method prints an array of objects as rows and columns?Answer:
console.table(). The optional second argument picks which columns to show. - What does
console.log("%d items", 3)print?Answer:3 items.%dis replaced by the next argument as an integer. - What happens when
console.assert(false, "Oops")runs?Answer: It printsAssertion failed: Oopsand the program continues. Unlikenode:assert,console.assertnever throws. - Which pair measures elapsed time?Answer:
console.time()andconsole.timeEnd().timeLogprints the time so far without stopping the timer. - Why might
console.log(obj)print[Object]?Answer: Nested objects deeper than 2 levels are collapsed. Useconsole.dir(obj, { depth: null })to see every level. - What does
console.trace()show?Answer: The call stack that led to the current line. It answers “which functions called this code?”. - When does a
debugger;statement pause the program?Answer: Only when a debugger is attached. With no debugger attached it is ignored. - In VS Code, which key steps over the current line while debugging?Answer: F10. F11 steps into a function call; Shift+F11 steps out.
- Why should tests use
node:assertorexpect()instead ofconsole.assert?Answer: They throw an error, so a failed check fails the test. A test runner only marks a test as failed when an error is thrown.
πΌ Interview Questions and Answers
Q1. What is the difference between console.log and console.error, and why does it matter in CI?
console.log writes to stdout and console.error (and console.warn) write to stderr. CI systems, Docker and shells can capture or redirect each stream separately, and some tools treat anything on stderr as a warning. Logging real errors with console.error makes failures easier to find and filter, while keeping normal progress logs on stdout.
Q2. How would you find which test step is slow in a Node.js script?
Wrap each step with console.time("step") / console.timeEnd("step"), or record performance.now() before and after for precise numbers you can assert on. For deeper analysis, run with node --cpu-prof or attach Chrome DevTools via node --inspect and record a performance profile. In Playwright, the trace viewer shows the duration of every action.
Q3. Explain how you would debug a failing function without adding console.log everywhere.
- Set a breakpoint on the first line of the function in VS Code (or add
debugger;). - Start with F5 (Node.js) so the debugger is attached.
- When it pauses, inspect the arguments in the Variables panel and add watch expressions.
- Step over (F10) line by line until a value differs from what you expect; step into (F11) helper calls when needed.
- Use the Call Stack panel to see who called the function with the bad input, then fix the root cause.
Q4. What is a call stack, and how does console.trace help?
The call stack is the list of functions that are currently running, with the most recent call on top. When an error occurs, its stack trace shows the same list. console.trace() prints the stack on demand, which shows the path that led to a line, for example which test or page-object method called a helper with the wrong data.
π who-called.js
function login(user) {
if (!user) console.trace("login called without a user");
}
function runTest() {
login(undefined);
}
runTest();
β¨οΈ Terminal
node who-called.js
π₯οΈ Output
Trace: login called without a user
at login (/home/you/js-course/who-called.js:2:22)
at runTest (/home/you/js-course/who-called.js:5:3)
at Object.<anonymous> (/home/you/js-course/who-called.js:7:1)
β Frequently Asked Questions
π€ Does console.log slow down my program?
A few logs do not matter. Logging inside loops that run thousands of times, or printing huge objects, can slow programs noticeably, so remove debug logs when you are done.
π€ Why do I not see console.log output from my web page in the terminal?
Code in a web page runs in the browser, so its logs appear in the browser DevTools Console (F12). Only code run by Node.js prints to the terminal. Playwright can forward page logs with page.on("console", ...).
π€ How do I clear the console?
Call console.clear(), press Ctrl+L in the browser console, or run clear (macOS/Linux) or cls (Windows) in the terminal.
π€ Should I leave console.log statements in my code?
Remove temporary debugging logs before committing. Keep only intentional logging, and in larger projects use a logging library that supports levels such as debug, info and error.
π Summary
console.log/infowrite to stdout;console.warn/errorwrite to stderr.console.table,group,time,count,dirandtracemake output easier to read and analyse.console.assertlogs failed checks but does not stop the program; tests need throwing assertions.- Breakpoints and the
debuggerstatement pause execution when a debugger is attached (VS Code F5, Chrome DevTools,node inspect). - Read stack traces from the top to find where an error happened and who called that code.
Next, continue with Lesson 6: Variables: var, let, const. Module 2 starts with variables, where you will use the console to inspect every value you create.
π¬ Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in