The JavaScript console API: log Levels, Formatting, table, group, time, count, assert and trace
Get far more from console than console.log: log levels and where output goes, format specifiers and CSS styling, logging objects without surprises, console.table, group, count, time and timeLog, assert and trace, plus logging habits for debugging and production.
kvi5hnuCode Sprout team member6 min readOn this page
console.log is usually the first JavaScript function anyone learns, and many developers never go further. The console object has about twenty methods that make debugging faster and output easier to read. It isn't part of the ECMAScript language itself (it's defined by a separate WHATWG standard), but every browser and Node.js implements it.
Runnable examples here show Node.js output; browser DevTools display the same information, often interactively (expandable objects, sortable tables).
Log levels
console.debug("cache miss for", key); // Verbose: hidden by default in Chrome DevTools
console.log("server started"); // Info
console.info("using config", path); // Info
console.warn("deprecated option: color"); // Warning: yellow
console.error("payment failed", err); // Error: red, includes a stack trace in browsers

Levels matter because:
- DevTools can filter by level, so you can hide verbose noise or show only errors.
- In Node,
log,infoanddebugwrite to standard output (stdout), whilewarn,error,assertfailures andtracewrite to standard error (stderr). Shells, Docker and log collectors can treat the two streams differently:node app.js > out.log 2> errors.log. - Error tracking tools often capture
console.errorcalls.
Logging several values and format specifiers
console.log accepts any number of arguments and prints them separated by spaces. Passing values as separate arguments is better than concatenating them into a string, because objects stay inspectable:
const user = { name: "Ana", roles: ["admin"] };
console.log("user:", user);
console.log("user: " + user);
console.log(`user: ${JSON.stringify(user)}`);
user: { name: 'Ana', roles: [ 'admin' ] }
user: [object Object]
user: {"name":"Ana","roles":["admin"]}
If the first argument is a string, it can contain format specifiers that consume the following arguments:
| Specifier | Inserts |
|---|---|
%s | a string |
%d, %i | an integer (in Node, %d keeps fractions) |
%f | a floating-point number |
%o, %O | an object (expandable in browsers) |
%c | CSS styles for the following text (browsers only) |
%% | a literal % |
console.log("%s scored %i points (%f%%)", "Ana", 87.9, 92.5);
Ana scored 87 points (92.5%)
In browsers, %c applies CSS, which is handy for making important log lines stand out:
console.log("%cBuild %s", "color: white; background: green; padding: 2px 6px", "v2.4.0");
Logging objects: two surprises
1. Browsers show objects live. In DevTools, an object logged with console.log(obj) is a reference. When you expand it later, you see its current contents, not its contents at the time of logging. If the object changed in between, the log looks wrong. Log a snapshot when that matters: console.log(structuredClone(obj)) or console.log(JSON.stringify(obj)).
2. Node abbreviates nested objects. Node prints objects with a depth limit of 2:
const config = { db: { primary: { host: { name: "db1", port: 5432 } } } };
console.log(config);
console.dir(config, { depth: null });
console.log(JSON.stringify(config, null, 2));
{ db: { primary: { host: [Object] } } }
{
db: { primary: { host: { name: 'db1', port: 5432 } } }
}
{
"db": {
"primary": {
"host": {
"name": "db1",
"port": 5432
}
}
}
}
console.dir(obj, { depth: null }) (Node) prints everything. In browsers, console.dir shows an object's properties as a tree, which is especially useful for DOM elements (which console.log shows as HTML).
Node also handles circular references and special values gracefully:
const node = { name: "loop" };
node.self = node;
console.log(node);
console.log(new Map([["a", 1]]), new Set([1]), [1, , 3], 10n, Symbol("id"));
<ref *1> { name: 'loop', self: [Circular *1] }
Map(1) { 'a' => 1 } Set(1) { 1 } [ 1, <1 empty item>, 3 ] 10n Symbol(id)
console.table
For arrays of objects (or objects of objects), console.table is far easier to scan than nested braces:
const scores = [
{ name: "Ana", score: 90, city: "Pune" },
{ name: "Bo", score: 72, city: "Oslo" },
];
console.table(scores);
console.table(scores, ["name", "score"]);
┌─────────┬───────┬───────┬────────┐
│ (index) │ name │ score │ city │
├─────────┼───────┼───────┼────────┤
│ 0 │ 'Ana' │ 90 │ 'Pune' │
│ 1 │ 'Bo' │ 72 │ 'Oslo' │
└─────────┴───────┴───────┴────────┘
┌─────────┬───────┬───────┐
│ (index) │ name │ score │
├─────────┼───────┼───────┤
│ 0 │ 'Ana' │ 90 │
│ 1 │ 'Bo' │ 72 │
└─────────┴───────┴───────┘
The optional second argument chooses columns. In DevTools, you can click column headers to sort.
console.group: nesting related output
console.group("Checkout #42");
console.log("validating cart");
console.group("payment");
console.log("card authorized");
console.groupEnd();
console.log("order saved");
console.groupEnd();
console.log("done");
Checkout #42
validating cart
payment
card authorized
order saved
done
Browsers render groups as collapsible sections; console.groupCollapsed starts one closed. Always pair each group with a groupEnd, even in error paths, or later output stays indented.
console.count: how many times?
function render(component) {
console.count(component);
}
render("Header");
render("Header");
render("Footer");
console.countReset("Header");
render("Header");
Header: 1
Header: 2
Footer: 1
Header: 1
Great for spotting functions that run more often than expected, like a component re-rendering on every keystroke. Without a label, the label is "default".
console.time: quick timing
console.time("load users");
const users = await fetchUsers();
console.timeLog("load users", "fetched", users.length); // intermediate time
renderUsers(users);
console.timeEnd("load users"); // "load users: 182.4ms"
Each label is an independent timer. It's fine for rough measurements; for precise benchmarks use performance.now() and many repetitions, and for real profiling use the DevTools Performance panel.
console.assert and console.trace
console.assert(cart.total >= 0, "negative total", cart);
// prints "Assertion failed: negative total {...}" only when the condition is false
console.assert logs only when its first argument is falsy. It doesn't throw or stop execution, so it's a debugging aid, not validation. (Node's assert module, used in tests, does throw.)
console.trace("label") prints the call stack at that point, answering "who called this function?":
function save() {
console.trace("save called");
}
// Trace: save called
// at save (app.js:2:11)
// at onSubmit (app.js:9:3)
// ...
Beyond console.log: better debugging tools
- The
debuggerstatement (article 45) pauses execution in DevTools at that line, letting you inspect every variable and step through code. For anything beyond a quick check, it's faster than adding logs. - Logpoints in DevTools add a log message at a line without editing the code.
- Conditional breakpoints pause only when an expression is true.
- In Node, run
node --inspect app.jsand openchrome://inspect(or use your editor's debugger) to get the same tools. - In the DevTools console,
$0is the currently selected element,copy(value)copies a value to the clipboard, andmonitorEvents(element)logs its events (these are DevTools conveniences, not part of JavaScript).
Logging in production
- Remove or gate debug logs before shipping: they leak internal details, clutter users' consoles and cost performance in hot paths. Many teams use a lint rule (
no-console) and stripconsole.debugin builds. - Never log secrets or personal data: passwords, tokens, full credit card numbers, health data. Logs are copied, retained and read by many people.
- On servers, use a structured logger (pino, winston or your platform's logger) that writes JSON with levels, timestamps and request IDs, so logs can be searched and alerted on.
- Log errors with their objects (
console.error("save failed", err)), not justerr.message, so the stack trace andcausesurvive.
Common questions
Why does my logged object show values that didn't exist yet when I logged it?
DevTools evaluates objects lazily when you expand them, so you see their current state. Log a copy (structuredClone(obj)) or a JSON string to capture the state at that moment.
Why does Node print [Object] instead of my nested data?
Node's default inspection depth is 2. Use console.dir(obj, { depth: null }) or JSON.stringify(obj, null, 2).
Is console.log slow?
Each call does real work (formatting, and in Node, writing to a stream). A few calls don't matter; thousands in a tight loop or on every animation frame can noticeably slow a program, and having DevTools open makes it slower. Remove logs from hot paths.
Does console.assert throw an error?
No. It only logs when the condition is false and execution continues. Use throw or a testing assertion library when failure must stop the program.
Summary
- Use levels deliberately:
debug,log/info,warn,error; in Node, warnings and errors go to stderr. - Pass objects as separate arguments; format specifiers (
%s %i %f %o %c) build formatted lines. - Browsers show logged objects live; Node abbreviates beyond depth 2 (
console.dir(obj, { depth: null })). console.tabledisplays tabular data,group/groupEndnests output,countcounts calls,time/timeLog/timeEndmeasure durations,assertlogs on failure, andtraceprints the call stack.- Prefer the debugger and breakpoints for real investigations; keep production logs structured, minimal and free of secrets.
Practice Questions
What does this code print?
console.log("%s has %i items", "cart", 3.7, "extra")
Answer
cart has 3 items extra. %i truncates 3.7 to 3, and leftover arguments are appended with spaces.
You suspect a function runs twice per click. Which console method confirms it fastest?
Answer
console.count("handler") inside the function: each call prints an increasing count.
Why might console.log(user) followed by user.name = "Bo" show name: "Bo" in Chrome's console?
Answer
Chrome shows a live reference: when you expand the object, it reads the current property values, which were changed after the log call.
Where does console.warn output go when you run node app.js > out.txt?
Answer
To the terminal, not the file. warn writes to stderr, and > redirects only stdout. Use 2> (or &> in bash) to capture stderr.
Previous: JavaScript Intl for Text: Sorting with Collator, Plural Rules, Segmenter, Display Names and Locales
Next: URLs in JavaScript: the URL Class, URLSearchParams, Encoding and Safe URL Building

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.