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.

Advertisement

πŸ“– 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.info is the same as console.log.
  • console.warn and console.error write 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:

SpecifierInserts
%sA string
%d or %iAn integer
%fA floating-point number
%o / %OAn object (detailed / plain)
%jJSON (Node.js only)
%cCSS 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.


Advertisement

πŸ—‚οΈ 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.


Advertisement

πŸ”¬ 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

  1. Open the file and click in the gutter left of a line number. A red dot (the breakpoint) appears.
  2. Press F5 and choose Node.js. The program stops at the breakpoint, before running that line.
  3. Hover over a variable, or look in the Variables panel, to see its value.
  4. 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

MethodUse it to
console.log / infoPrint general messages and values
console.warn / errorPrint warnings and errors (to stderr)
console.tableShow arrays of objects as a table
console.group / groupEndIndent related messages
console.time / timeLog / timeEndMeasure how long code takes
console.count / countResetCount how often a line runs
console.assertPrint a message only when a condition is false
console.dirPrint deep objects with { depth: null }
console.tracePrint the call stack
console.clearClear the console (browser and terminal)

Advertisement

πŸ“ 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 Pune

Q2. 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: 100000

The 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 characters

The 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: 2

Q6. 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.

  1. Where does console.error() write its output in Node.js?
  2. Which method prints an array of objects as rows and columns?
  3. What does console.log("%d items", 3) print?
  4. What happens when console.assert(false, "Oops") runs?
  5. Which pair measures elapsed time?
  6. Why might console.log(obj) print [Object]?
  7. What does console.trace() show?
  8. When does a debugger; statement pause the program?
  9. In VS Code, which key steps over the current line while debugging?
  10. Why should tests use node:assert or expect() instead of console.assert?

πŸ’Ό 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.

  1. Set a breakpoint on the first line of the function in VS Code (or add debugger;).
  2. Start with F5 (Node.js) so the debugger is attached.
  3. When it pauses, inspect the arguments in the Variables panel and add watch expressions.
  4. Step over (F10) line by line until a value differs from what you expect; step into (F11) helper calls when needed.
  5. 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)

Advertisement

❓ 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/info write to stdout; console.warn/error write to stderr.
  • console.table, group, time, count, dir and trace make output easier to read and analyse.
  • console.assert logs failed checks but does not stop the program; tests need throwing assertions.
  • Breakpoints and the debugger statement 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