Какое выражение выведет отладочные данные на консоль браузера javascript
Перейти к содержимому

Какое выражение выведет отладочные данные на консоль браузера javascript

  • автор:

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.

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

Jesse Hall

Jesse Hall

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

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

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

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

Console Output

But wait – it gets better!

If we only want the brands, just console.table(devices, [‘brand’]) !

Console Output

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.

Отладка в браузере

Давайте отвлечёмся от написания кода и поговорим о его отладке.

Отладка – это процесс поиска и исправления ошибок в скрипте. Все современные браузеры и большинство других сред разработки поддерживают инструменты для отладки – специальный графический интерфейс, который сильно упрощает отладку. Он также позволяет по шагам отследить, что именно происходит в нашем коде.

Мы будем использовать браузер Chrome, так как у него достаточно возможностей, в большинстве других браузеров процесс будет схожим.

Панель «Исходный код» («Sources»)

Версия Chrome, установленная у вас, может выглядеть немного иначе, однако принципиальных отличий не будет.

  • Работая в Chrome, откройте тестовую страницу.
  • Включите инструменты разработчика, нажав F12 (Mac: Cmd + Opt + I ).
  • Щёлкните по панели Sources («исходный код»).

При первом запуске получаем следующее:

Кнопка-переключатель откроет вкладку со списком файлов.

Кликните на неё и выберите hello.js в дереве файлов. Вот что появится:

Интерфейс состоит из трёх зон:

  1. В зоне File Navigator (панель для навигации файлов) показаны файлы HTML, JavaScript, CSS, включая изображения, используемые на странице. Здесь также могут быть файлы различных расширений Chrome.
  2. Зона Code Editor (редактор кода) показывает исходный код.
  3. Наконец, зона JavaScript Debugging (панель отладки JavaScript) отведена для отладки, скоро мы к ней вернёмся.

Чтобы скрыть список ресурсов и освободить экранное место для исходного кода, щёлкните по тому же переключателю .

Консоль

При нажатии на клавишу Esc в нижней части экрана вызывается консоль, где можно вводить команды и выполнять их клавишей Enter .

Результат выполнения инструкций сразу же отображается в консоли.

Например, результатом 1+2 будет 3 , а вызов функции hello("debugger") ничего не возвращает, так что результатом будет undefined :

Точки останова (breakpoints)

Давайте разберёмся, как работает код нашей тестовой страницы. В файле hello.js щёлкните на номере строки 4 . Да-да, щёлкайте именно по самой цифре, не по коду.

Ура! Вы поставили точку останова. А теперь щёлкните по цифре 8 на восьмой линии.

Вот что в итоге должно получиться (синим это те места, по которым вы должны щёлкнуть):

Точка останова – это участок кода, где отладчик автоматически приостановит исполнение JavaScript.

Пока исполнение поставлено «на паузу», мы можем просмотреть текущие значения переменных, выполнить команды в консоли, другими словами, выполнить отладку кода.

В правой части графического интерфейса мы видим список точек останова. А когда таких точек выставлено много, да ещё и в разных файлах, этот список поможет эффективно ими управлять:

  • Быстро перейдите к точке останова в коде (нажав на неё на правой панели).
  • Временно отключите точку останова, сняв с неё галочку.
  • Удалите точку останова, щёлкнув правой кнопкой мыши и выбрав Remove (Удалить).
  • …и так далее.

Щелчок правой кнопкой мыши по номеру строки позволяет создать условную точку останова. Она сработает только в тот момент, когда выражение, которое вы должны указать при создании такой точки, истинно.

Это удобно, когда нам нужно остановиться только при определённом значении переменной или для определённых параметров функции.

Команда debugger

Выполнение кода можно также приостановить с помощью команды debugger прямо изнутри самого кода:

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

Остановимся и оглядимся

В нашем примере функция hello() вызывается во время загрузки страницы, поэтому для начала отладки (после того, как мы поставили точки останова) проще всего её перезагрузить. Нажмите F5 (Windows, Linux) или Cmd + R (Mac).

Выполнение прервётся на четвёртой строчке (где находится точка останова):

Чтобы понять, что происходит в коде, щёлкните по стрелочкам справа:

Watch – показывает текущие значения для любых выражений.

Вы можете нажать на + и ввести выражение. Отладчик покажет его значение, автоматически пересчитывая его в процессе выполнения.

Call Stack – показывает цепочку вложенных вызовов.

В текущий момент отладчик находится внутри вызова hello() , вызываемого скриптом в index.html (там нет функции, поэтому она называется “анонимной”).

Если вы нажмёте на элемент стека (например, «anonymous»), отладчик перейдёт к соответствующему коду, и нам представляется возможность его проанализировать.

Scope показывает текущие переменные.

Local показывает локальные переменные функций, а их значения подсвечены прямо в исходном коде.

В Global перечисляются глобальные переменные (то есть вне каких-либо функций).

Там также есть ключевое слово this , которое мы ещё не изучали, но скоро изучим.

Пошаговое выполнение скрипта

А теперь давайте пошагаем по нашему скрипту.

Для этого есть кнопки в верхней части правой панели. Давайте рассмотрим их.

– «Resume»: продолжить выполнение, быстрая клавиша F8 .

Возобновляет выполнение кода. Если больше нет точек останова, то выполнение просто продолжается, без контроля отладчиком.

Вот, что мы увидим, кликнув на неё:

Выполнение кода возобновилось, дошло до другой точки останова внутри say() , и отладчик снова приостановил выполнение. Обратите внимание на пункт «Call stack» справа: в списке появился ещё один вызов. Сейчас мы внутри say() .

– «Step»: выполнить следующую команду, быстрая клавиша F9 .

Выполняет следующую инструкцию. Если мы нажмём на неё сейчас, появится alert .

Нажатие на эту кнопку снова и снова приведёт к пошаговому выполнению всех инструкций скрипта одного за другим.

– «Step over»: выполнить следующую команду, но не заходя внутрь функции, быстрая клавиша F10 .

Работает аналогично предыдущей команде «Step», но ведёт себя по-другому, если следующая инструкция является вызовом функции (имеется ввиду: не встроенная, как alert , а объявленная нами функция).

Если сравнить, то команда «Step» переходит во вложенный вызов функцию и приостанавливает выполнение в первой строке, в то время как «Step over» выполняет вызов вложенной функции незаметно для нас, пропуская её внутренний код.

Затем выполнение приостанавливается сразу после вызова функции.

Это хорошо, если нам не интересно видеть, что происходит внутри вызова функции.

– «Step into», быстрая клавиша F11 .

Это похоже на «Step», но ведёт себя по-другому в случае асинхронных вызовов функций. Если вы только начинаете изучать JavaScript, то можете не обращать внимания на разницу, так как у нас ещё нет асинхронных вызовов.

На будущее просто помните, что команда «Step» игнорирует асинхронные действия, такие как setTimeout (вызов функции по расписанию), которые выполняются позже. «Step into» входит в их код, ожидая их, если это необходимо. См. DevTools manual для получения более подробной информации.

– «Step out»: продолжить выполнение до завершения текущей функции, быстрая клавиша Shift + F11 .

Продолжает выполнение и останавливает его в самой последней строке текущей функции. Это удобно, когда мы случайно вошли во вложенный вызов, используя , но это нас не интересует, и мы хотим продолжить его до конца как можно скорее.

– активировать/деактивировать все точки останова(breakpoints).

Эта кнопка не влияет на выполнение кода, она лишь позволяет массово включить/отключить точки останова.

– включить/отключить автоматическую паузу в случае ошибки.

При включении, если открыты инструменты разработчика, ошибка при выполнении скрипта автоматически приостанавливает его. Затем мы можем проанализировать переменные в отладчике, чтобы понять, что пошло не так. Поэтому, если наш скрипт умирает с ошибкой, мы можем открыть отладчик, включить эту опцию и перезагрузить страницу, чтобы увидеть, где он умирает и каков контекст в этот момент.

Щелчок правой кнопкой мыши по строке кода открывает контекстное меню с отличной опцией под названием «Continue to here» («продолжить до этого места»).

Это удобно, когда мы хотим перейти на несколько шагов вперёд к строке, но лень устанавливать точку останова (breakpoint).

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

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

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