console: log() method
The console.log() method outputs a message to the web console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects.
Note: This feature is available in Web Workers
Syntax
Parameters
A list of JavaScript objects to output. Objects are output in the order listed. Please be warned that if you log objects in the latest versions of Chrome and Firefox, what you get logged on the console is a reference to the object, which is not necessarily the ‘value’ of the object at the moment in time you call console.log() , but it is the value of the object at the moment you open the console.
A JavaScript string containing zero or more substitution strings.
JavaScript objects with which to replace substitution strings within msg . This gives you additional control over the format of the output.
See Outputting text to the console in the documentation of console for details.
Return value
Logging objects
Information about an object is lazily retrieved. This means that the log message shows the content of an object at the time when it’s first viewed, not when it was logged. For example:
This will output <> . However, if you expand the object’s details, you will see prop: 123 .
If you are going to mutate your object and you want to prevent the logged information from being updated, you can deep-clone the object before logging it. A common way is to JSON.stringify() and then JSON.parse() it:
There are other alternatives that work in browsers, such as structuredClone() , which are more effective at cloning different types of objects.
Console log()
The log() method writes (logs) a message to the console.
The log() method is useful for testing purposes.
When testing console methods, be sure to have the console view visible.
Press F12 to open the console veiw.
Syntax
Parameters
| Parameter | Description |
| message | Required. The message to write to the console. |
More Examples
Write an object to the console:
Write an array to the console:
Browser Support
console.log() is supported in all browsers:
| Chrome | IE | Edge | Firefox | Safari | Opera |
| Yes | 8-11 | Yes | Yes | Yes | Yes |

COLOR PICKER


Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Mastering Console log
![]()
Knowing your tools can make a significant difference when it comes to getting things done. Despite JavaScript’s reputation as being difficult to debug, if you keep a couple of tricks up your sleeve errors and bugs will take less time to resolve.
We’ve put together a list of some debugging tips that you may not know, but might want to keep in mind for next time you find yourself needing to debug your JavaScript code!
The console. log() is a function that writes a message to log on the debugging console, such as Webkit or Firebug. In a browser, you will not see anything on the screen. It logs a message to a debugging console. It is only available in Firefox with Firebug and Webkit based browsers (Chrome and Safari).
The console. log() is a function in JavaScript that is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user.
We all know its basics:
console.log(‘Hello!’); //log a simple ‘Hello!’ message but is not return something because showing ‘undefined’
console.info(‘Something happened’); //same as console log
console.warn(‘Something strange happened…’); //same as console log but showing with warning
console.error(‘Something error message); //same as console log but showing with error
JavaScript has left-to-right associativity
So here we discuss more advanced console log features :
1.console.log(true + 3); and console.log(false + 3);
Return value = 4
Why does true + 3 = 4?
JavaScript can be a weird language at times. This article will explain to you.
In JavaScript, when the plus operator is placed between a number and a boolean, the boolean is converted into a number
In the above code, we add 3 to true and then 3 to false. Our answers are 4, and 3, respectively. What we can determine from this example is that JavaScript coerces a true boolean into the value of 1, and a false boolean into the value of 0.
2. console.log(false — 3); and console.log(true — 3);
Same as the previous one, the value of false = 0 and true = 1 then the answer is -3 and -2.
3. console.log(true == 1); and console.log(false == 0);
We get true for both equations. Now that we know the values that true and false coerce to, the condition is to check the equation and ‘==’ means both values are the same because of return True.
Example: What is 3 + true + true + false — true ?
Answer: 4
4. console.log(‘Number + Number:’, 4 + 8); and console.log(‘String + Number:’, “4” + 8);
What happens when we add a string to an actual number
We get 12 and 48 when the plus operator is placed between to operands, and both are number then answer 12 but one is a string, it will convert the other number or boolean to a string and concatenate them. By this logic: ‘4’ + 8 becomes ‘4’ + ‘8’ and we get an answer of ‘48’.
An addition in JavaScript has left-to-right associativity. This means that when we have an equation with multiple + operators, the left-most operator is evaluated first.
But what happens if our string value is the last in our equation? Would anything change? Run the following code and let’s see. Notice that the difference between this example and the example above is the location of our string variable.
console.log(1 + 1 + “1”) answer is 21.Yes! That’s because the order of operations is very important. In this instance, JavaScript evaluates the first + before anything else: 1 + 1 which equals 2. Only then do we move on and add in the string value of ‘1’. Now String concatenation occurs and the result is ‘21’.
5. console.log(‘String + Number:’, “50” + 50); and console.log(‘Negative + String + Number:’, -”50" + 50);
What if we attempt to negate a string with the negative operator and then add it to a number? For example, -“50" + 50. What would the answer be?
Output: String + Number: 5050
Negative + String + Number: 0
As expected, our String + Number result is “5050” due to string concatenation. However, the negation in the second equation changes things. The minus sign before “50” is a unary minus operator that will coerce the string into a number and make it negative. Thus, our equation becomes -50 + 50 which equals 0.
Seeing as the minus operator coerced our string value into a number, what happens if we use the minus operator on a different value of a string? Let’s look at this example: -”giddyup” + 409. JavaScript is going to try to coerce our “giddyup” string into a number value. But will it be able to?
console.log(-”giddyup” + 409);
Output: NaN
When JavaScript fails to coerce a number in the example above, we are left with NaN (Not A Number).
6. console.log(true && 2)
Answer is 2
Here Logical operators have typically used with Boolean (logical) values. When they are, they return a Boolean value. However, the && and || operators return the value of one of the specified operands, so if these operators are used with non-Boolean values, they will return a non-Boolean value.
The logical operators are described in the table
If a value can be converted to true, the value is so-called truthy. If a value can be converted to false, the value is so-called falsy.
So the first expression is true then return the second expression means return value 2
7. console.log(false && 2)
The answer is false because in && operator mandatory to true both values and here first value is false then the return false
8. console.log(true || 2)
The answer is true because in || operator not mandatory to true both values and here first value is true then return the first value true.
9. console.log(false || 2)
The answer is 2 because in || operator not mandatory to true both values and here first value is false then return second value 2
10. console.log(a > 0 && b > 0);
const a = 3;
const b = -2;
console.log(a > 0 && b > 0);
The answer is False because the first expression is true and second is false then return the second expression means return value false.
11. console.time(); and console.timeEnd();
It can be super useful to know exactly how long something has taken to execute, especially when debugging slow loops. You can even set up multiple timers by assigning a label to the method.
Example:
console.time(‘Timer’);
var items = [];
for(var i = 0; i < 100; i++) <
items.push(
>
console.timeEnd(‘Timer’);
12. console.memory
If your performance issue is trickier, and you are looking for a memory leak, you might like to try and utilize console.memory to check out your heap size status.
13. console.count(‘Name’)
In a case of multiple function or code, you can use console.count(‘?’) to keep count of how many times your code is run.
var items = [];
for(var i = 0; i < 5; i++) <
items.push(
console.count(‘check’)
>
14. console.assert()
Writes an error message to the console if the assertion is false. If the assertion is true, nothing happens.
The console.assert() method was implemented differently in older Node.js versions than the console.assert() method available in browsers. In browsers, calling console.assert() with a falsy assertion prints message to the console without interrupting execution of subsequent code. Before Node.js v10.0.0, however, a false assertion would also cause an AssertionError to be thrown. This discrepancy was fixed with Node v10, so that console.assert() now acts the same in both Node and the browser.
Syntax:
console.assert(assertion, obj1 [, obj2, …, objN]);
console.assert(assertion, msg [, subst1, …, substN]);
assertion
Any boolean expression. If the assertion is false, the message is written to the console.
obj1 … objN
A list of JavaScript objects to output. The string representations of each of these objects are appended together in the order listed and output.
msg
A JavaScript string containing zero or more substitution strings.
subst1 … substN
JavaScript objects with which to replace substitution strings within msg. This parameter gives you additional control over the format of the output.
Example:
15. console.group(‘group’) and console.groupEnd(‘group’)
If you want to organize your log, so this feature is useful. console.group() and console.groupEnd() is a small and useful tool in console history. using this console group your console logs are grouped, while each grouping creates another level in the hierarchy. to reduce the Calling groupEnd.
16. String substitutions
You can incorporate variables using string substitutions. These references should be types (%s = string, %i = integer, %o = object, %f = float).
console.log(‘Hii %s, Your age is %i.’, ‘Nitish’, 29)
17. console.table()
Sometimes, you have a complex set of objects that you want to view. You can either console.log them and scroll through the list, or break out the console. table helper. It makes it easier to see what you’re dealing with!
18. console.trace()
You probably know JavaScript frameworks, produce a lot of code — quickly.
It creates views and triggers events, so eventually, you’ll want to know what caused the function call.
Since JavaScript is not a very structured language, it can sometimes be hard to get an overview of what happened and when. This is when console. trace (or just trace in the console) comes handy to be able to debug JavaScript.
Команды для работы с JavaScript-консолью в браузерах и повышение производительности труда программиста
Если вы занимаетесь веб-программированием, это значит, что вам не надо рассказывать о том, насколько в вашей работе важна отладка. Нередко для записи данных в логи, для их форматирования или вывода на экран используют внешние библиотеки, не учитывая при этом того факта, что в распоряжении программистов имеются JavaScript-команды для работы с консолями, которые встроены в браузеры. И обладают эти консоли гораздо более серьёзными возможностями, чем может показаться на первый взгляд.

Что такое консоль?
Консоль JavaScript — это механизм, интегрированный в современные браузеры, который поддерживает встроенные инструменты разработки в интерфейсе, напоминающем командную строку. С использованием консоли разработчик может делать следующее:
- Просматривать журналы ошибок и предупреждений, возникающих на веб-странице.
- Взаимодействовать с веб-страницей, используя команды JavaScript.
- Отлаживать приложения и работать с DOM непосредственно из браузера.
- Исследовать и анализировать сетевую активность.
Методы console.log, console.error, console.warn и console.info
Вероятно, наиболее часто используемыми методами при работе с консолью являются console.log() , console.error() , console.warn() и console.info() . Этим методам можно передавать один или несколько параметров. Система вычисляет значение каждого из них и объединяет все результаты в строку, части которой разделены пробелами. В случае с объектами или массивами эти команды позволяют выводить их в таком виде, который позволяет просматривать их содержимое. Вот как это выглядит.

Использование различных команд для вывода данных в консоль
Метод console.group
Метод console.group() позволяет собирать серии вызовов console.log() (а также — других подобных методов) в группы, содержимое которых можно сворачивать и разворачивать. Пользоваться этим методом очень просто: после вызова console.group() (или после console.groupCollapsed() , если группу требуется вывести сразу в свёрнутом виде) нужно поместить все вызовы console.log() , которые надо сгруппировать. Затем, в конце набора команд, которые требуется сгруппировать, надо поместить команду console.groupEnd() . Рассмотри пример.
В консоль, после выполнения этого фрагмента кода, попадёт следующее.

Группировка данных в консоли с помощью метода console.group()
Метод console.table
После того, как я узнал о существовании метода console.table() , моя жизнь изменилась навсегда. Например, использование обычной команды console.log() при выводе JSON-кода или больших JSON-массивов — это сущий кошмар. Метод console.table() позволяет выводить сложные структуры данных внутри симпатичных таблиц, столбцам которых можно давать имена, передавая их в качестве параметров (не все браузеры поддерживают эту возможность console.table() ). Вот пример работы с этой командой.
То, что получилось, и выглядит отлично, и способно облегчить отладку.

Табличное оформление выводимых данных с помощью console.table()
Методы console.count, console.time и console.timeEnd
Методы console.count() , console.time() и console.timeEnd() можно назвать чем-то вроде швейцарского ножа для разработчика, который занимается отладкой приложений. Так, метод console.count() позволяет подсчитывать количество собственных вызовов и выводить его в консоль с заданной меткой. Метод console.time() позволяет запустить именованный таймер (имя передаётся ему в качестве параметра, на одной странице может присутствовать до 10000 таймеров). Для того чтобы остановить конкретный таймер, используется команда console.timeEnd() с меткой таймера, передаваемой в качестве параметра. Она останавливает таймер и выводит время его работы в консоль. Вот как пользоваться этими методами.
А вот как выглядит результат работы этого кода в консоли.

Использование методов console.count(), console.time() и console.timeEnd()
Методы console.trace и console.assert
Методы console.trace() и console.assert() позволят выводить из места их вызова информацию о стеке. Представьте себе, что вы занимаетесь разработкой JS-библиотеки и хотите сообщить пользователю о том, где возникла ошибка. В подобном случае эти методы могут оказаться весьма полезными. Метод console.assert() похож на console.trace() , разница между ними заключается в том, что console.assert() выведет данные лишь в том случае, если не выполнится переданное ему условие. Вот как работать с этими методами.
Несложно заметить, что вывод, генерируемый этим фрагментом кода, выглядит так же, как нечто подобное выглядело бы в React (или в любой другой библиотеке), когда фреймворк сообщает о возникновении исключения.

Результат использования команд console.assert() и console.trace()
Команды для работы с консолью и продакшн-код
Команды для работы с консолью нужны на этапе разработки и отладки приложений. Это значит, что когда придёт время выпуска продукта, эти команды придётся из кода удалить. Об этом можно просто забыть и, через некоторое время после сборки продакшн-версии проекта, заметить, что программа пишет что-то в консоль тогда, когда в этом нет никакой необходимости. Не стоит нагружать компьютеры ненужной работой, пусть и такой, казалось бы, незначительной, как вывод данных в консоль. В то же время, учитывая то, что команды для работы с консолью могут пригодиться в ходе доработки приложения, лучше всего не удалять их из исходного кода программы насовсем, а убирать их лишь из её продакшн-версии. Тут нам на помощь придут средства для сборки проектов. Так, я постоянно пользуюсь Webpack, и на работе, и в собственных проектах. Этот инструмент позволяет удалять все ненужные команды по работе с консолью (он способен отличить их от других команд) из продакшн-сборок с использованием uglifyjs-webpack-plugin.
Эта конфигурация очень проста, но она облегчает повседневную работу программиста и избавляет от проблемы забытых команд по работе с консолью.
Итоги
В этом материале мы рассказали о некоторых полезных командах для работы с консолью. Они позволяют, с помощью инструментов, являющихся частью современных браузеров, решать множество задач, которые сопутствуют разработке и отладке клиентских JavaScript-приложений.
Уважаемые читатели! Какие команды для работы с JavaScript-консолью вы используете?