Console API in JavaScript
Introduction
The console object is your first debugging tool in the browser DevTools and in Node.js terminals. Beyond log, it offers grouping, tables, timers, and assertions. Learning these methods speeds up everyday development without extra libraries.
Prerequisites
console.log and Friends
// Basic output
const user = { id: 1, name: "Ada" };
console.log("user loaded", user);
// warn and error stand out in DevTools
console.warn("disk almost full");
console.error("payment failed", { code: "CARD_DECLINED" });console.table
// Tabular view for arrays of objects
const rows = [
{ sku: "A1", qty: 2 },
{ sku: "B2", qty: 1 },
];
console.table(rows);Grouping
// Collapsible groups in DevTools
console.group("checkout");
console.log("validate cart");
console.log("charge card");
console.groupEnd();Nested: console.groupCollapsed("details").
Timers on Console
// Measure elapsed time
console.time("fetch");
for (let i = 0; i < 1e6; i++) {
// simulate work
}
console.timeEnd("fetch");Distinct from setTimeout—see timers.
console.assert
// Logs only if condition is false
function divide(a, b) {
console.assert(b !== 0, "divisor must not be zero");
return a / b;
}
console.log(divide(10, 2));
divide(10, 0);console.trace
// Print stack trace
function inner() {
console.trace("called from");
}
function outer() {
inner();
}
outer();Node vs Browser
Both support the core API. Browser adds styling (%c) and links to source lines; Node prints to stdout/stderr. Avoid leaving verbose console.log in hot production paths—use structured logging libraries instead.
Mini Example: Debug Pipeline Steps
function runPipeline(steps) {
console.group("pipeline");
steps.forEach((step, i) => {
console.log(`step ${i + 1}:`, step.name);
step.run();
});
console.groupEnd();
}
runPipeline([
{ name: "load", run: () => {} },
{ name: "transform", run: () => {} },
{ name: "save", run: () => {} },
]);FAQ
Does console.log block execution?
It runs synchronously but is relatively slow—fine for debugging, not for high-volume production logs.
Can I log objects by reference?
Yes—expanding in DevTools shows live object state at inspect time.
Replace debugger statement?
debugger pauses if DevTools open; console only prints—different tools.
What comes next?
Timers—setTimeout and setInterval.