JavaScript Console.log() Example – How to Print to the Console in JS

Jesse Hall

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.
console.log
Let’s start with a very basic log example.
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.
But what if we have multiple values that we want to log?
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.
But that’s too much work. Just wrap them with curly braces! Now you get an object with the named values.

Console Output
You can do the same thing with an object.
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?
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:
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() .
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?
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!
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() .
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() .
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() .
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.
In this example, we have very simple functions that just call each other. Then, in the last function, we call console.trace() .

Console Output
Tables
Here’s one of the most mind-blowing uses for console: console.table() .
So let’s set up some data to log:
Now we’ll log this data using console.table(devices) .

Console Output
But wait – it gets better!
If we only want the brands, just console.table(devices, [‘brand’]) !

Console Output
How about a more complex example? In this example, we’ll use jsonplaceholder.
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 .
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.
YouTube: There’s More To Console Than Log
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.
Use JavaScript console.log() like a PRO
![]()
Using console.log() for JavaScript debugging is one of the most common practice among the developers even if many frown upon it. I must admit that I am still using console.log() in my day to day coding and I am not alone, like me, the majority of JavaScript developers are still using it for finding the errors in their code (Refer Developer Report — 2016). One of the main reasons for using it, its the simplest thing to do and off-course old habits die hard!
Below are the mentioned features and tips for console.log(). Click on them to directly view them.
String substitution
This is a technique which utilizes the placeholders in a string which are replaced by the other arguments that you pass to the console method. The following placeholders can be used.
- string = %s
- integer = %i or %d
- object = %o or %O
- float = %f
- apply CSS rules = %c
Custom CSS styles for console.log()
By default there are 4 different ways of outputting the messages to the console ( log , info , warn , error ). All the methods work the same way and the difference being each of them show with different color based on the log-level and different icon.
Apart from these default functions, you can also define custom CSS styles for the logs by applying CSS rules in the string substitution with the %c placeholder and passing the CSS rules as a string argument. You can also add more than one %c to the string.
# Console
console.time() can be used to measure how long a task in your code takes to run.
(opens new window) is called, the elapsed time, in milliseconds, since the original .time() call is calculated and logged. Because of this behavior, you can call .timeEnd() multiple times with the same label to log the elapsed time since the original .time() call was made.
Example 1:
Example 2:
# Formatting console output
Displays Sam has 100 points .
The full list of format specifiers in Javascript is:
| Specifier | Output |
|---|---|
| %s | Formats the value as a string |
| %i or %d | Formats the value as an integer |
| %f | Formats the value as a floating point value |
| %o | Formats the value as an expandable DOM element |
| %O | Formats the value as an expandable JavaScript object |
| %c | Applies CSS style rules to the output string as specified by the second parameter |
# Advanced styling
When the CSS format specifier ( %c ) is placed at the left side of the string, the print method will accept a second parameter with CSS rules which allow fine-grained control over the formatting of that string:

It is possible to use multiple %c format specifiers:
- any substring to the right of a %c has a corresponding parameter in the print method;
- this parameter may be an emtpy string, if there is no need to apply CSS rules to that same substring;
- if two %c format specifiers are found, the 1 st (encased in %c ) and 2 nd substring will have their rules defined in the 2 nd and 3 rd parameter of the print method respectively.
- if three %c format specifiers are found, then the 1 st , 2 nd and 3 rd substrings will have their rules defined in the 2 nd , 3 rd and 4 th parameter respectively, and so on.

# Using groups to indent output
Output can be idented and enclosed in a collapsible group in the debugging console with the following methods:
-
: creates a collapsed group of entries that can be expanded through the disclosure button in order to reveal all the entries performed after this method is invoked; : creates an expanded group of entries that can be collapsed in order to hide the entries after this method is invoked.
The identation can be removed for posterior entries by using the following method:
-
: exits the current group, allowing newer entries to be printed in the parent group after this method is invoked.
Groups can be cascaded to allow multiple idented output or collapsible layers within eachother:

(opens new window) = Collapsed group expanded => 
# Printing to a browser’s debugging console
A browser’s debugging console can be used in order to print simple messages. This debugging or web console
(opens new window) can be directly opened in the browser ( F12 key in most browsers – see Remarks below for further information) and the log method of the console Javascript object can be invoked by typing the following:
Then, by pressing Enter , this will display My message in the debugging console.
console.log() can be called with any number of arguments and variables available in the current scope. Multiple arguments will be printed in one line with a small space between them.
The log method will display the following in the debugging console:
Beside plain strings, console.log() can handle other types, like arrays, objects, dates, functions, etc.:
Nested objects may be collapsed:
Certain types such as Date objects and function s may be displayed differently:
# Other print methods
In addition to the log method, modern browsers also support similar methods:

The above image shows all the functions, with the exception of timeStamp , in Chrome version 56.
These methods behave similarly to the log method and in different debugging consoles may render in different colors or formats.
In certain debuggers, the individual objects information can be further expanded by clicking the printed text or a small triangle (►) which refers to the respective object properties. These collapsing object properties can be open or closed on log. See the console.dir
(opens new window) for additional information on this
# Including a stack trace when logging — console.trace()
Will display this in the console:
Note: Where available it’s also useful to know that the same stack trace is accessible as a property of the Error object. This can be useful for post-processing and gathering automated feedback.
# Tabulating values — console.table()
In most environments, console.table() can be used to display objects and arrays in a tabular format.
For example:
| (index) | value |
|---|---|
| 0 | "Hello" |
| 1 | "world" |
| (index) | value |
|---|---|
| "foo" | "bar" |
| "bar" | "baz" |
console.table(personArr, [‘name’, ‘personId’]);

# Counting — console.count()
(opens new window) places a counter on the object’s value provided as argument. Each time this method is invoked, the counter is increased (with the exception of the empty string » ). A label together with a number is displayed in the debugging console according to the following format:
label represents the value of the object passed as argument and X represents the counter’s value.
An object’s value is always considered, even if variables are provided as arguments:
Strings with numbers are converted to Number objects:
Functions point always to the global Function object:
Certain objects get specific counters associated to the type of object they refer to:
# Empty string or absence of argument
If no argument is provided while sequentially inputting the count method in the debugging console, an empty string is assumed as parameter, i.e.:
# Debugging with assertions — console.assert()
Writes an error message to the console if the assertion is false . Otherwise, if the assertion is true , this does nothing.

Multiple arguments can be provided after the assertion–these can be strings or other objects–that will only be printed if the assertion is false :

(opens new window) does not throw an AssertionError (except in Node.js
(opens new window) ), meaning that this method is incompatible with most testing frameworks and that code execution will not break on a failed assertion.
# Clearing the console — console.clear()
You can clear the console window using the console.clear() method. This removes all previously printed messages in the console and may print a message like "Console was cleared" in some environments.
# Displaying objects and XML interactively — console.dir(), console.dirxml()
console.dir(object) displays an interactive list of the properties of the specified JavaScript object. The output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects.

console.dirxml(object) prints an XML representation of the descendant elements of object if possible, or the JavaScript representation if not. Calling console.dirxml() on HTML and XML elements is equivalent to calling console.log() .
Example 1:

Example 2:

Example 3:

# Syntax
- void console.log(obj1 [, obj2, . objN]);
- void console.log(msg [, sub1, . subN]);
# Parameters
| Parameter | Description |
|---|---|
| obj1 . objN | A list of JavaScript objects whose string representations are outputted in the console |
| msg | A JavaScript string containing zero or more substitution strings. |
| sub1 . subN | JavaScript objects with which to replace substitution strings within msg. |
# Remarks
The information displayed by a debugging/web console
(opens new window) that can be consulted through console.dir(console) . Besides the console.memory property, the methods displayed are generally the following (taken from Chromium’s output):
# Opening the Console
In most current browsers, the JavaScript Console has been integrated as a tab within Developer Tools. The shortcut keys listed below will open Developer Tools, it might be necessary to switch to the right tab after that.
# Chrome
Opening the “Console” panel of Chrome’s DevTools:
-
— Ctrl + Shift + J — Ctrl + Shift + I , then click on the “Web Console” tab **or** press ESC to toggle the console on and off — F12 , then click on the “Console” tab **or** press ESC to toggle the console on and off
Mac OS: Cmd + Opt + J
# Firefox
Opening the “Console” panel in Firefox’s Developer Tools:
-
— Ctrl + Shift + K — Ctrl + Shift + I , then click on the “Web Console” tab **or** press ESC to toggle the console on and off — F12 , then click on the “Web Console” tab **or** press ESC to toggle the console on and off
Mac OS: Cmd + Opt + K
# Edge and Internet Explorer
Opening the “Console” panel in the F12 Developer Tools:
- F12 , then click on the “Console” tab
# Safari
Opening the “Console” panel in Safari’s Web Inspector you must first enable the develop menu in Safari’s Preferences

Then you can either pick "Develop->Show Error Console" from the menus or press ⌘ + Option + C
# Opera
Opening the “Console” in opera:
- Ctrl + Shift + I ,then click on the “Console” tab
# Compatibility
When using or emulating Internet Explorer 8 or earlier versions (e.g. through Compatibility View / Enterprise Mode) the console will only be defined when the Developer Tools are active, so console.log() statements can cause an exception and prevent code from executing. To mitigate this, you can check to see if the console is available before you log:
Or at the start of your script you can identify if the console is available and if not, define a null function to catch all of your references and prevent exceptions.
Note this second example will stop all console logs even if the developer window has been opened.
Использование JavaScript-консоли в браузерах
Сегодня мы публикуем заметку, посвящённую особенностям использования JavaScript-консоли в браузерах, лежащим за пределами широко известной команды console.log() . Собственно говоря, эта команда представляет собой простейший инструмент для отладки программ, который позволяет выводить что-либо в консоль. Однако знание некоторых особенностей этого инструмента позволит тем, кто им пользуется, повысить эффективность работы.
Команда console.log() и имена переменных
Простейший вариант использования console.log() заключается, например, в выводе некоей строки или объекта. Например, выведем в консоль строку:
Теперь представим себе, что в консоль нужно вывести несколько объектов. Например — таких:
Пожалуй, логичнее всего будет воспользоваться для решения этой задачи несколькими командами вида console.log(variable) . Хотя данные в консоль и попадают, при их выводе понятной становится одна проблема.
Взглянем на то, что выводится в консоль.

В консоли нет имён переменных
Как можно видеть, имён переменных, foo и bar , здесь нет. Объекты, пользуясь значком в виде стрелки в левых частях строк, можно разворачивать, но даже так, глядя на внутреннюю структуру объектов, понять, какой именно объект выведен в консоль, может быть весьма непросто. В решении этой проблемы нам помогут вычисляемые имена свойств объектов. А именно, эта особенность объектных литералов, появившаяся в ES6, позволяет пользоваться удобной конструкцией следующего вида:
При таком подходе в консоль попадёт объект, имена свойств которого будут представлять собой имена переменных-объектов, которые нужно вывести. Кроме того, это позволяет избавиться от некоторых вызовов console.log() , используемых ранее для вывода объектов по отдельности.
Команда console.table()
Улучшать внешний вид того, что программа выводит в консоль, можно и дальше, оформив содержимое объектов в виде таблицы. Это хорошо скажется на читаемости информации. А именно, речь идёт о том, что если вы выводите в консоль объекты с одинаковыми именами свойств, или массивы похожих объектов, вы можете воспользоваться командой console.table() . Вот как выглядит результат выполнения команды вида console.table(< foo, bar >) .

Команда console.table() в действии
Команда console.group()
Эту команду можно использовать в том случае, если нужно сгруппировать некие связанные данные и создать структуры из вложенных групп, которые повышают удобство работы с такими данными.
Кроме того, этот подход можно использовать в тех случаях, когда в некоей функции выполняется несколько команд вывода чего-либо в консоль, и нужно, чтобы можно было бы чётко, с одного взгляда, отделить результаты выполнения таких команд от других.
Предположим, мы выводим в консоль сведения о неких пользователях:
Вот как выглядят результаты работы этого кода.

Группировка результатов работы команд вывода данных в консоль
При использовании команды console.group() группы, по умолчанию, выводятся в развёрнутом виде. Для того, чтобы они выводились свёрнутыми, вместо этой команды можно воспользоваться командой console.groupCollapsed() . Для того, чтобы просмотреть содержимое такой группы, её понадобится развернуть с помощью значка, находящегося слева от имени группы.
Команды console.warn() и console.error()
В зависимости от ситуации, для того чтобы подчеркнуть важность некоторых сообщений, выводимых в консоль, вам могут пригодиться команды console.warn() и console.error() . Они используются, соответственно, для вывода предупреждений и ошибок.

Предупреждения и ошибки
Возможно, вам пригодится и команда console.info() , которая предназначена для вывода информационных сообщений.
В настройке внешнего вида сообщений, выводимых в консоль, можно пойти и ещё дальше, самостоятельно их стилизовав. Для стилизации текстов, выводимых в консоль, можно воспользоваться директивой %c . Это может оказаться полезным, например, для организации визуального разделения сведений, поступающих от подсистем выполнения обращений к неким API, от подсистем, ответственных за обработку событий, генерируемых пользователем, и так далее. Главное тут — выработать некие правила стилизации и их придерживаться. Вот пример настройки внешнего вида данных, выводимых в консоль:
Тут же можно настраивать и другие CSS-свойства текста, наподобие font-size и font-style .

Стилизация данных, выводимых в консоль
Команда console.trace()
Команда console.trace() выводит в консоль результаты трассировки стека и позволяет судить о том, что произошло в определённом месте программы во время её выполнения. Например, существуют некоторые методы, которые, в определённых ситуациях, нужно вызывать лишь один раз, скажем — методы для удаления информации из базы данных. Проверить, действительно ли выполняется лишь однократный вызов подобного метода, можно с помощью console.trace() . Эта команда позволяет вывести в консоль сведения, которые помогают проконтролировать правильность работы внутренних механизмов программ.
Команда console.time()
Одна из важных задач, встающая перед фронтенд-разработчиком, заключается в том, чтобы обеспечить высокую скорость работы кода. Команда console.time() позволяет замерять время выполнения операций и выводить то, что удалось выяснить, в консоль. Например, исследуем с помощью этой команды пару циклов:
Взглянем на то, что попало в консоль после выполнения этого кода.

Результаты использования console.time()
Итоги
В этом материале мы рассмотрели некоторые полезные мелочи, касающиеся вывода данных в консоли браузеров. Если раньше вы об этих возможностях не знали — надеемся, теперь у вас появились новые полезные JavaScript-инструменты.
Уважаемые читатели! Если вы занимаетесь разработкой больших JavaScript-проектов — просим вас рассказать о том, какими средствами вы решаете в них проблемы логирования.