The console
object provides access to the browser’s
debugging console (e.g. the Web console in Firefox).
The specifics of how it works varies from browser to browser, but there is a de facto
set of features that are typically provided.
The console
object can be accessed from any global object. Window
on
browsing scopes and WorkerGlobalScope
as specific variants in workers via the
property console. It’s exposed as Window.console
, and can be referenced as
console
. For example:
console.log("Failed to open the specified link");
This page documents the Methods available on the console
object and
gives a few Usage examples.
Note: This feature is available in Web Workers
Instance methods
console.assert()
-
Log a message and stack trace to console if the first argument is
false
. console.clear()
-
Clear the console.
console.count()
-
Log the number of times this line has been called with the given label.
console.countReset()
-
Resets the value of the counter with the given label.
console.debug()
-
Outputs a message to the console with the log level
debug
. console.dir()
-
Displays an interactive listing of the properties of a specified JavaScript object. This listing lets you use disclosure triangles to examine the contents of child objects.
console.dirxml()
-
Displays an XML/HTML Element representation of the specified object if possible or the JavaScript Object view if it is not possible.
console.error()
-
Outputs an error message. You may use string substitution and additional arguments with this method.
console.exception()
Non-standard
Deprecated
-
An alias for
error()
. console.group()
-
Creates a new inline group, indenting all following output by another level. To move back out a level, call
groupEnd()
. console.groupCollapsed()
-
Creates a new inline group, indenting all following output by another level. However, unlike
group()
this starts with the inline group collapsed requiring the use of a disclosure button to expand it. To move back out a level, callgroupEnd()
. console.groupEnd()
-
Exits the current inline group.
console.info()
-
Informative logging of information. You may use string substitution and additional arguments with this method.
console.log()
-
For general output of logging information. You may use string substitution and additional arguments with this method.
console.profile()
Non-standard
-
Starts the browser’s built-in profiler (for example, the Firefox performance tool). You can specify an optional name for the profile.
console.profileEnd()
Non-standard
-
Stops the profiler. You can see the resulting profile in the browser’s performance tool (for example, the Firefox performance tool).
console.table()
-
Displays tabular data as a table.
console.time()
-
Starts a timer with a name specified as an input parameter. Up to 10,000 simultaneous timers can run on a given page.
console.timeEnd()
-
Stops the specified timer and logs the elapsed time in milliseconds since it started.
console.timeLog()
-
Logs the value of the specified timer to the console.
console.timeStamp()
Non-standard
-
Adds a marker to the browser performance tool’s timeline (Chrome or Firefox).
console.trace()
-
Outputs a stack trace.
console.warn()
-
Outputs a warning message. You may use string substitution and additional arguments with this method.
Examples
Outputting text to the console
The most frequently-used feature of the console is logging of text and other data. There are several categories of output you can generate, using the console.log()
, console.info()
, console.warn()
, console.error()
, or console.debug()
methods. Each of these results in output styled differently in the log, and you can use the filtering controls provided by your browser to only view the kinds of output that interest you.
There are two ways to use each of the output methods; you can pass in a list of objects whose string representations get concatenated into one string, then output to the console, or you can pass in a string containing zero or more substitution strings followed by a list of objects to replace them.
Outputting a single object
The simplest way to use the logging methods is to output a single object:
const someObject = { str: "Some text", id: 5 };
console.log(someObject);
The output looks something like this:
Outputting multiple objects
You can also output multiple objects by listing them when calling the logging method, like this:
const car = "Dodge Charger";
const someObject = { str: "Some text", id: 5 };
console.info("My first car was a", car, ". The object is:", someObject);
The output will look like this:
My first car was a Dodge Charger. The object is: {str:"Some text", id:5}
Using string substitutions
When passing a string to one of the console
object’s methods that accepts a string (such as log()
), you may use these substitution strings:
%o
or%O
-
Outputs a JavaScript object. Clicking the object name opens more information about it in the inspector.
%d
or%i
-
Outputs an integer. Number formatting is supported, for example
console.log("Foo %.2d", 1.1)
will output the number as two significant figures with a leading 0:Foo 01
. %s
-
Outputs a string.
%f
-
Outputs a floating-point value. Formatting is supported, for example
console.log("Foo %.2f", 1.1)
will output the number to 2 decimal places:Foo 1.10
.
Note: Precision formatting doesn’t work in Chrome.
Each of these pulls the next argument after the format string off the parameter list. For example:
for (let i = 0; i < 5; i++) {
console.log("Hello, %s. You've called me %d times.", "Bob", i + 1);
}
The output looks like this:
Hello, Bob. You've called me 1 times. Hello, Bob. You've called me 2 times. Hello, Bob. You've called me 3 times. Hello, Bob. You've called me 4 times. Hello, Bob. You've called me 5 times.
Styling console output
You can use the %c
directive to apply a CSS style to console output:
console.log(
"This is %cMy stylish message",
"color: yellow; font-style: italic; background-color: blue;padding: 2px"
);
The text before the directive will not be affected, but the text after the directive will be styled using the CSS declarations in the parameter.
You may use %c
multiple times:
console.log(
"Multiple styles: %cred %corange",
"color: red",
"color: orange",
"Additional unformatted message"
);
The properties usable along with the %c
syntax are as follows (at least, in Firefox — they may differ in other browsers):
background
and its longhand equivalentsborder
and its longhand equivalentsborder-radius
box-decoration-break
box-shadow
clear
andfloat
color
cursor
display
font
and its longhand equivalentsline-height
margin
outline
and its longhand equivalentspadding
text-*
properties such astext-transform
white-space
word-spacing
andword-break
writing-mode
Note: The console message behaves like an inline element by default. To see the effects of padding
, margin
, etc. you should set it to for example display: inline-block
.
Using groups in the console
You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call console.group()
. The console.groupCollapsed()
method is similar but creates the new block collapsed, requiring the use of a disclosure button to open it for reading.
To exit the current group, call console.groupEnd()
. For example, given this code:
console.log("This is the outer level");
console.group("First group");
console.log("In the first group");
console.group("Second group");
console.log("In the second group");
console.warn("Still in the second group");
console.groupEnd();
console.log("Back to the first group");
console.groupEnd();
console.debug("Back to the outer level");
The output looks like this:
Timers
You can start a timer to calculate the duration of a specific operation. To start one, call the console.time()
method, giving it a name as the only parameter. To stop the timer, and to get the elapsed time in milliseconds, just call the console.timeEnd()
method, again passing the timer’s name as the parameter. Up to 10,000 timers can run simultaneously on a given page.
For example, given this code:
console.time("answer time");
alert("Click to continue");
console.timeLog("answer time");
alert("Do a bunch of other stuff…");
console.timeEnd("answer time");
Will log the time needed by the user to dismiss the alert box, log the time to the console, wait for the user to dismiss the second alert, and then log the ending time to the console:
Notice that the timer’s name is displayed both when the timer is started and when it’s stopped.
Note: It’s important to note that if you’re using this to log the timing for network traffic, the timer will report the total time for the transaction, while the time listed in the network panel is just the amount of time required for the header.
If you have response body logging enabled, the time listed for the response header and body combined should match what you see in the console output.
Stack traces
The console object also supports outputting a stack trace; this will show you the call path taken to reach the point at which you call console.trace()
. Given code like this:
function foo() {
function bar() {
console.trace();
}
bar();
}
foo();
The output in the console looks something like this:
Specifications
Specification |
---|
Console Standard # console-namespace |
Browser compatibility
BCD tables only load in the browser
Notes
- At least in Firefox, if a page defines a
console
object, that object overrides the one built into Firefox.
See also
- Firefox Developer Tools
- Web console — how the Web console in Firefox handles console API calls
- about:debugging — how to see console output when the debugging target is a mobile device
Other implementations
Logging messages to the console is a very basic way to diagnose and troubleshoot minor issues in your code.
But, did you know that there is more to console
than just log
? In this article, I’ll show you how to print to the console in JS, as well as all of the things you didn’t know console
could do.
Firefox Multi-line Editor Console
If you’ve never used the multi-line editor mode in Firefox, you should give it a try right now!
Just open the console, Ctrl+Shift+K
or F12
, and in the top right you will see a button that says «Switch to multi-line editor mode». Alternatively, you can press Ctrl+B
.
This gives you a multi-line code editor right inside Firefox.
Let’s start with a very basic log example.
let x = 1
console.log(x)
Type that into the Firefox console and run the code. You can click the «Run» button or press Ctrl+Enter
.
In this example, we should see «1» in the console. Pretty straightforward, right?
Multiple Values
Did you know that you can include multiple values? Add a string to the beginning to easily identify what it is you are logging.
let x = 1
console.log("x:", x)
But what if we have multiple values that we want to log?
let x = 1
let y = 2
let z = 3
Instead of typing console.log()
three times we can include them all. And we can add a string before each of them if we wanted, too.
let x = 1
let y = 2
let z = 3
console.log("x:", x, "y:", y, "z:", z)
But that’s too much work. Just wrap them with curly braces! Now you get an object with the named values.
let x = 1
let y = 2
let z = 3
console.log( {x, y, z} )
You can do the same thing with an object.
let user = {
name: 'Jesse',
contact: {
email: 'codestackr@gmail.com'
}
}
console.log(user)
console.log({user})
The first log will print the properties within the user object. The second will identify the object as «user» and print the properties within it.
If you are logging many things to the console, this can help you to identify each log.
Variables within the log
Did you know that you can use portions of your log as variables?
console.log("%s is %d years old.", "John", 29)
In this example, %s
refers to a string option included after the initial value. This would refer to «John».
The %d
refers to a digit option included after the initial value. This would refer to 29.
The output of this statement would be: «John is 29 years old.».
Variations of logs
There are a few variations of logs. There is the most widely used console.log()
. But there is also:
console.log('Console Log')
console.info('Console Info')
console.debug('Console Debug')
console.warn('Console Warn')
console.error('Console Error')
These variations add styling to our logs in the console. For instance, the warn
will be colored yellow, and the error
will be colored red.
Note: The styles vary from browser to browser.
Optional Logs
We can print messages to the console conditionally with console.assert()
.
let isItWorking = false
console.assert(isItWorking, "this is the reason why")
If the first argument is false, then the message will be logged.
If we were to change isItWorking
to true
, then the message will not be logged.
Counting
Did you know that you can count with console?
for(i=0; i<10; i++){
console.count()
}
Each iteration of this loop will print a count to the console. You will see «default: 1, default: 2», and so on until it reaches 10.
If you run this same loop again you will see that the count picks up where it left off; 11 — 20.
To reset the counter we can use console.countReset()
.
And, if you want to name the counter to something other than «default», you can!
for(i=0; i<10; i++){
console.count('Counter 1')
}
console.countReset('Counter 1')
Now that we have added a label, you will see «Counter 1, Counter 2», and so on.
And to reset this counter, we have to pass the name into countReset
. This way you can have several counters running at the same time and only reset specific ones.
Track Time
Besides counting, you can also time something like a stopwatch.
To start a timer we can use console.time()
. This will not do anything by itself. So, in this example, we will use setTimeout()
to emulate code running. Then, within the timeout, we will stop our timer using console.timeEnd()
.
console.time()
setTimeout(() => {
console.timeEnd()
}, 5000)
As you would expect, after 5 seconds, we will have a timer end log of 5 seconds.
We can also log the current time of our timer while it’s running, without stopping it. We do this by using console.timeLog()
.
console.time()
setTimeout(() => {
console.timeEnd()
}, 5000)
setTimeout(() => {
console.timeLog()
}, 2000)
In this example, we will get our 2 second timeLog
first, then our 5 second timeEnd
.
Just the same as the counter, we can label timers and have multiple running at the same time.
Groups
Another thing that you can do with log
is group them. ?
We start a group by using console.group()
. And we end a group with console.groupEnd()
.
console.log('I am not in a group')
console.group()
console.log('I am in a group')
console.log('I am also in a group')
console.groupEnd()
console.log('I am not in a group')
This group of logs will be collapsible. This makes it easy to identify sets of logs.
By default, the group is not collapsed. You can set it to collapsed by using console.groupCollapsed()
in place of console.group()
.
Labels can also be passed into the group()
to better identify them.
Stack Trace
You can also do a stack trace with console
. Just add it into a function.
function one() {
two()
}
function two() {
three()
}
function three() {
console.trace()
}
one()
In this example, we have very simple functions that just call each other. Then, in the last function, we call console.trace()
.
Tables
Here’s one of the most mind-blowing uses for console: console.table()
.
So let’s set up some data to log:
let devices = [
{
name: 'iPhone',
brand: 'Apple'
},
{
name: 'Galaxy',
brand: 'Samsung'
}
]
Now we’ll log this data using console.table(devices)
.
But wait – it gets better!
If we only want the brands, just console.table(devices, ['brand'])
!
How about a more complex example? In this example, we’ll use jsonplaceholder.
async function getUsers() {
let response = await fetch('https://jsonplaceholder.typicode.com/users')
let data = await response.json()
console.table(data, ['name', 'email'])
}
getUsers()
Here we are just printing the «name» and «email». If you console.log
all of the data, you will see that there are many more properties for each user.
Style ?
Did you know that you can use CSS properties to style your logs?
To do this, we use %c
to specify that we have styles to add. The styles get passed into the second argument of the log
.
console.log("%c This is yellow text on a blue background.", "color:yellow; background-color:blue")
You can use this to make your logs stand out.
Clear
If you are trying to troubleshoot an issue using logs, you may be refreshing a lot and your console may get cluttered.
Just add console.clear()
to the top of your code and you’ll have a fresh console every time you refresh. ?
Just don’t add it to the bottom of your code, lol.
Thanks for Reading!
If you want to revisit the concepts in this article via video, you can check out this video-version I made here.
I’m Jesse from Texas. Check out my other content and let me know how I can help you on your journey to becoming a web developer.
- Subscribe To My YouTube
- Say Hello! Instagram | Twitter
- Sign Up For My Newsletter
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
Stability: 2 — Stable
The node:console
module provides a simple debugging console that is similar to
the JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Console
class with methods such asconsole.log()
,console.error()
, and
console.warn()
that can be used to write to any Node.js stream. - A global
console
instance configured to write toprocess.stdout
and
process.stderr
. The globalconsole
can be used without calling
require('node:console')
.
Warning: The global console object’s methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the note on process I/O for
more information.
Example using the global console
:
console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr
Example using the Console
class:
const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err
Class: Console
The Console
class can be used to create a simple logger with configurable
output streams and can be accessed using either require('node:console').Console
or console.Console
(or their destructured counterparts):
const { Console } = require('node:console');
const { Console } = console;
new Console(stdout[, stderr][, ignoreErrors])
new Console(options)
options
{Object}stdout
{stream.Writable}stderr
{stream.Writable}ignoreErrors
{boolean} Ignore errors when writing to the underlying
streams. Default:true
.colorMode
{boolean|string} Set color support for thisConsole
instance.
Setting totrue
enables coloring while inspecting values. Setting to
false
disables coloring while inspecting values. Setting to
'auto'
makes color support depend on the value of theisTTY
property
and the value returned bygetColorDepth()
on the respective stream. This
option can not be used, ifinspectOptions.colors
is set as well.
Default:'auto'
.inspectOptions
{Object} Specifies options that are passed along to
util.inspect()
.groupIndentation
{number} Set group indentation.
Default:2
.
Creates a new Console
with one or two writable stream instances. stdout
is a
writable stream to print log or info output. stderr
is used for warning or
error output. If stderr
is not provided, stdout
is used for stderr
.
const output = fs.createWriteStream('./stdout.log'); const errorOutput = fs.createWriteStream('./stderr.log'); // Custom simple logger const logger = new Console({ stdout: output, stderr: errorOutput }); // use it like console const count = 5; logger.log('count: %d', count); // In stdout.log: count 5
The global console
is a special Console
whose output is sent to
process.stdout
and process.stderr
. It is equivalent to calling:
new Console({ stdout: process.stdout, stderr: process.stderr });
console.assert(value[, ...message])
value
{any} The value tested for being truthy....message
{any} All arguments besidesvalue
are used as error message.
console.assert()
writes a message if value
is falsy or omitted. It only
writes a message and does not otherwise affect execution. The output always
starts with "Assertion failed"
. If provided, message
is formatted using
util.format()
.
If value
is truthy, nothing happens.
console.assert(true, 'does nothing'); console.assert(false, 'Whoops %s work', 'didn't'); // Assertion failed: Whoops didn't work console.assert(); // Assertion failed
console.clear()
When stdout
is a TTY, calling console.clear()
will attempt to clear the
TTY. When stdout
is not a TTY, this method does nothing.
The specific operation of console.clear()
can vary across operating systems
and terminal types. For most Linux operating systems, console.clear()
operates similarly to the clear
shell command. On Windows, console.clear()
will clear only the output in the current terminal viewport for the Node.js
binary.
console.count([label])
label
{string} The display label for the counter. Default:'default'
.
Maintains an internal counter specific to label
and outputs to stdout
the
number of times console.count()
has been called with the given label
.
> console.count() default: 1 undefined > console.count('default') default: 2 undefined > console.count('abc') abc: 1 undefined > console.count('xyz') xyz: 1 undefined > console.count('abc') abc: 2 undefined > console.count() default: 3 undefined >
console.countReset([label])
label
{string} The display label for the counter. Default:'default'
.
Resets the internal counter specific to label
.
> console.count('abc'); abc: 1 undefined > console.countReset('abc'); undefined > console.count('abc'); abc: 1 undefined >
console.debug(data[, ...args])
data
{any}...args
{any}
The console.debug()
function is an alias for console.log()
.
console.dir(obj[, options])
obj
{any}options
{Object}showHidden
{boolean} Iftrue
then the object’s non-enumerable and symbol
properties will be shown too. Default:false
.depth
{number} Tellsutil.inspect()
how many times to recurse while
formatting the object. This is useful for inspecting large complicated
objects. To make it recurse indefinitely, passnull
. Default:2
.colors
{boolean} Iftrue
, then the output will be styled with ANSI color
codes. Colors are customizable;
see customizingutil.inspect()
colors. Default:false
.
Uses util.inspect()
on obj
and prints the resulting string to stdout
.
This function bypasses any custom inspect()
function defined on obj
.
console.dirxml(...data)
...data
{any}
This method calls console.log()
passing it the arguments received.
This method does not produce any XML formatting.
console.error([data][, ...args])
data
{any}...args
{any}
Prints to stderr
with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3) (the arguments are all passed to
util.format()
).
const code = 5; console.error('error #%d', code); // Prints: error #5, to stderr console.error('error', code); // Prints: error 5, to stderr
If formatting elements (e.g. %d
) are not found in the first string then
util.inspect()
is called on each argument and the resulting string
values are concatenated. See util.format()
for more information.
console.group([...label])
...label
{any}
Increases indentation of subsequent lines by spaces for groupIndentation
length.
If one or more label
s are provided, those are printed first without the
additional indentation.
console.groupCollapsed()
An alias for console.group()
.
console.groupEnd()
Decreases indentation of subsequent lines by spaces for groupIndentation
length.
console.info([data][, ...args])
data
{any}...args
{any}
The console.info()
function is an alias for console.log()
.
console.log([data][, ...args])
data
{any}...args
{any}
Prints to stdout
with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to printf(3) (the arguments are all passed to
util.format()
).
const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout
See util.format()
for more information.
console.table(tabularData[, properties])
tabularData
{any}properties
{string[]} Alternate properties for constructing the table.
Try to construct a table with the columns of the properties of tabularData
(or use properties
) and rows of tabularData
and log it. Falls back to just
logging the argument if it can’t be parsed as tabular.
// These can't be parsed as tabular data console.table(Symbol()); // Symbol() console.table(undefined); // undefined console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); // ┌─────────┬─────┬─────┐ // │ (index) │ a │ b │ // ├─────────┼─────┼─────┤ // │ 0 │ 1 │ 'Y' │ // │ 1 │ 'Z' │ 2 │ // └─────────┴─────┴─────┘ console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); // ┌─────────┬─────┐ // │ (index) │ a │ // ├─────────┼─────┤ // │ 0 │ 1 │ // │ 1 │ 'Z' │ // └─────────┴─────┘
console.time([label])
label
{string} Default:'default'
Starts a timer that can be used to compute the duration of an operation. Timers
are identified by a unique label
. Use the same label
when calling
console.timeEnd()
to stop the timer and output the elapsed time in
suitable time units to stdout
. For example, if the elapsed
time is 3869ms, console.timeEnd()
displays «3.869s».
console.timeEnd([label])
label
{string} Default:'default'
Stops a timer that was previously started by calling console.time()
and
prints the result to stdout
:
console.time('bunch-of-stuff'); // Do a bunch of stuff. console.timeEnd('bunch-of-stuff'); // Prints: bunch-of-stuff: 225.438ms
console.timeLog([label][, ...data])
label
{string} Default:'default'
...data
{any}
For a timer that was previously started by calling console.time()
, prints
the elapsed time and other data
arguments to stdout
:
console.time('process'); const value = expensiveProcess1(); // Returns 42 console.timeLog('process', value); // Prints "process: 365.227ms 42". doExpensiveProcess2(value); console.timeEnd('process');
console.trace([message][, ...args])
message
{any}...args
{any}
Prints to stderr
the string 'Trace: '
, followed by the util.format()
formatted message and stack trace to the current position in the code.
console.trace('Show me'); // Prints: (stack trace will vary based on where trace is called) // Trace: Show me // at repl:2:9 // at REPLServer.defaultEval (repl.js:248:27) // at bound (domain.js:287:14) // at REPLServer.runBound [as eval] (domain.js:300:12) // at REPLServer.<anonymous> (repl.js:412:12) // at emitOne (events.js:82:20) // at REPLServer.emit (events.js:169:7) // at REPLServer.Interface._onLine (readline.js:210:10) // at REPLServer.Interface._line (readline.js:549:8) // at REPLServer.Interface._ttyWrite (readline.js:826:14)
console.warn([data][, ...args])
data
{any}...args
{any}
The console.warn()
function is an alias for console.error()
.
Inspector only methods
The following methods are exposed by the V8 engine in the general API but do
not display anything unless used in conjunction with the inspector
(--inspect
flag).
console.profile([label])
label
{string}
This method does not display anything unless used in the inspector. The
console.profile()
method starts a JavaScript CPU profile with an optional
label until console.profileEnd()
is called. The profile is then added to
the Profile panel of the inspector.
console.profile('MyLabel'); // Some code console.profileEnd('MyLabel'); // Adds the profile 'MyLabel' to the Profiles panel of the inspector.
console.profileEnd([label])
label
{string}
This method does not display anything unless used in the inspector. Stops the
current JavaScript CPU profiling session if one has been started and prints
the report to the Profiles panel of the inspector. See
console.profile()
for an example.
If this method is called without a label, the most recently started profile is
stopped.
console.timeStamp([label])
label
{string}
This method does not display anything unless used in the inspector. The
console.timeStamp()
method adds an event with the label 'label'
to the
Timeline panel of the inspector.