Что такое console log в javascript
Перейти к содержимому

Что такое console log в javascript

  • автор:

Console.log()

Список объектов JavaScript для вывода. Объекты выводятся в том порядке, в котором они были указаны при вызове метода. Пожалуйста, обратите внимание, что если вы логируете объекты в последних версиях Chrome и Firefox, в консоль залогируется не значение объекта, а ссылка на него. Это означает, что, возможно, в консоль будет выведено не значение объекта на момент вызова console.log() , а будет выведено значение объекта на момент открытия консоли.

Строка JavaScript, содержащая 0 и более подстановочных символов для замены (см. subst1 . substN ).

JavaScript-объекты, с помощью которых произойдёт замена подстановочных символов в msg . Это даст вам дополнительный контроль над форматом вывода.

Больше подробностей смотрите в разделе Вывод текста в консоль (en-US) документации console .

Спецификация

Specification
Console Standard
# log

Совместимость с браузерами

BCD tables only load in the browser

Отличия от console.dir()

Вы можете спросить какая разница между console.dir() и console.log(). Это полезное отличие.

  • console.log выводит элемент как HTML-дерево
  • console.dir выводит элемент как JSON-объект

А именно, console.log даёт специальное обращение к DOM-элементам, тогда как console.dir — нет. Это особенно полезно, когда нужно видеть полное представление DOM JS-объектов.

Больше информации об этой и других функциях в Chrome Console API reference.

Логирование объектов

Не используйте console.log(obj); , Используйте console.log(JSON.parse(JSON.stringify(obj))); .

Так вы можете быть уверены, что видите значение obj в момент, его логирования.

# 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:

output

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.

multiple CSS specifiers output

# 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:

Collapsed group

(opens new window) = Collapsed group expanded => Expanded group

# 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:

Console functions

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’]);

enter image description here

# 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.

output

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 :

Assertion with multiple objects as parameters

(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.

enter image description here

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:

enter image description here

Example 2:

enter image description here

Example 3:

enter image description here

# 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

safari 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.

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

Unlock Full Access

COLOR PICKER

colorpicker

Join our Bootcamp!

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.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *