📜 ⬆️ ⬇️

Use console to the full

The console.log () method is a great way to display debugging information without disturbing the user. But did you know that the console object has a lot of other equally useful methods? Very rarely, developers use this functionality, limited to non-blocking alert. Well, let's fix this situation.


A quick note: the use of a debugging code can adversely affect performance. Remove it from the production version.

More than just messages


Before diving into the little-known console methods, let's take a look at the console.log functionality in more detail. For example, the ability to pass any number of arguments:
var foo = {baz: "tubular", goo: "rad"}, bar = "baz"; console.log("string",1,foo.goo,bar,foo.baz); // string 1 rad baz tubular 

')
As a result, all passed arguments will be displayed and separated by a space. This, of course, is good, but it would be even better if we could somehow derive all these arguments in the form of a beautifully formatted message. But wait ... we can!

If you are familiar with the printf () function in other languages, then we hasten to please: console.log () knows how to behave in a similar way. Take the last example and pass the first argument in a slightly modified form.
 var foo = {baz: "tubular", goo: "rad"}, bar = "baz"; console.log( "%s theory is %d %s concept. I can only describe it as %s and %s", "string", 1, foo.goo, bar, foo.baz ); // string theory is 1 rad concept. I can only describe it as baz and tubular 


What is% s?

Great question! These are control sequences that are replaced with their corresponding values ​​(in order of priority). % s means "treat the value as a string",% d - as a number (You can also use% i or% f).

Each occurrence of such a sequence will be replaced by the next argument in order. The first entry is at the first (after the first argument string, of course), and so on.

The order of using the arguments can be changed manually by using the $ character and assigning the argument number that we want to print to it:
 var foo = {baz: "tubular", goo: "rad"}, bar = "baz"; console.log( "%2$d theory is %d %s concept. I can only describe it as %s and %s", "string",1,foo.goo,bar,foo.baz ); // 1 theory is 0 baz concept. I can only describe it as tubular and %s string 


This command as it says "I will start with the second argument and continue, starting with the next one." As you can see, the sequences that did not have enough arguments remained intact.

The first argument (format string) also participates in the numbering (it comes from scratch) of the arguments. Thus, in our example, the last argument will have the number 5. But we specified only 5 arguments and, at the same time, started from the second. Therefore, the last control sequence of the arguments was not inherited, and it has not changed.

To fix this, you can change the format of the string so that the “pointer” not the next element is synchronized with the argument list at a certain point. Then everything will work as expected.
 var foo = {baz: "tubular", goo: "rad"}, bar = "baz"; console.log( "%2$d theory is %1$s %3$s concept. I can only describe it as %s and %s", "string",1,foo.goo,bar,foo.baz ); // 1 theory is string rad concept. I can only describe it as baz and tubular 


In order for the arguments to be output correctly, we need to change the order of output of the second and third elements. Other elements are already in the correct position, so there is no need to indicate their positions. Arguments will be used in the following order: 2, 1, 3, 4, 5.

String formatting is a powerful tool, and I covered only the tip of the iceberg. Try to play on your own and read what Joe Hewitts writes about the console .

Different message types


There are a couple more methods like log but different in appearance. Namely: console.info (), console.warn () and console.error ().
 console.info("%s numbers %d, %d and %d","hello",1,2,3); // hello numbers 1, 2 and 3 console.warn("%s numbers %d, %d and %d","hello",1,2,3); console.error("%s numbers %d, %d and %d","hello",1,2,3); 

console.info (), console.warn () and console.error () in Firebug.

All three methods are able to output strings in accordance with the format and take any number of arguments.

DOM's logs


When you need to somehow point the DOM node to the logs, it’s best to use the console.dir () or console.dirxml () methods, which can enumerate the properties of the element or output the HTML of the element.
 console.dir(document.documentElement); console.dirxml(document.documentElement); 

Meet console.dir () and console.dirxml () in Chrome.

Grouping


Sometimes it is useful to group logs to simplify working with them. To do this, there are methods console.group (), console.groupCollapsed () and console.groupEnd ().
 console.group("Overlord"); console.log("Overlord stuff"); console.group("Lord"); console.log("Overlord stuff"); console.group("Minion"); console.log("Minion stuff"); console.groupEnd(); console.groupCollapsed("Servant"); console.log("Servant stuff"); 

Grouping in the Safari console.

As you can see, the successive group calls create subfolders. To close a folder, use the console.groupEnd () method. The console.groupCollapsed () method is similar to console.group () with the only exception that the group with all its contents will be initially collapsed.

Profiling and Measurements


The console also allows you to accurately measure time using the console.time () method and console.timeEnd (). Place the call of the first one before the code whose execution time you want to measure, and the second after.
 console.time("Execution time took"); // Some code to execute console.timeEnd("Execution time took"); 

An example of how console.time () and console.timeEnd () work in Firefox

Timers are linked by tags (passed by the first argument and can be any string), so you can start several timers at the same time. When console.timeEnd () works, a message will be displayed with a label and elapsed time in milliseconds.

In addition to measuring time, you can profile your code and display a profiling stack, which shows in detail where and how much time the browser has spent.
 console.profile(); // Some code to execute console.profileEnd(); 

Profiling in Chrome.

Assertions


When you are working on a complex project, it is important to cover the unit code with tests. This will avoid stupid mistakes and possible regressions. Fortunately, the console includes assertions.

Assert'y allow you to enforce the rules in the code and be sure that the results of the execution of this code are consistent with expectations. The console.assert () method allows for elementary code testing: if something goes wrong, an exception will be thrown. The first argument can be anything you want: a function, a test for equality, or a test for the existence of an object.
 var a = 1, b = "1"; console.assert(a === b, "A doesn't equal B"); 

Assert in chrome

The assert method accepts a condition that is required to be executed (in this case, a simple strict equality check) and, with the second argument, a message that will be output to the console with the exception thrown if the first condition is not met.

Browser Support


Most of the listed methods are supported quite well. IE8 +, Firefox with a firebug extension, Opera, or a webkit browser like Safari or Chrome. There are, however, some differences: Firefox, Safari and Chrome are more widely supported. The easiest way to check compatibility is by running console.dir (console), the result of which is the output of the console object with all its methods.

Opera with Dragonfly supports most methods, with the exception of string formatting and profiling (although the profile, profileEnd methods are implemented, these are just stubs).

IE8 also supports a lot of goodies, including string formatting and assertions, but not time measurements, profiling, dir or dirxml methods.

It should be noted that firebug lite can add some methods to the console in browsers that do not support them.

This is not a complete list of what is in the console, but I listed the most useful features that greatly simplify the process of debugging and testing. Use acquired knowledge and do not limit yourself to logging strings.

Extra


So, it was a very free translation of the article, but now I would like to add a little of myself:
Node.JS (branch 0.2) supports the log, info, warn, error, dir, time / timeEnd, assert, and trace methods.
log cannot change the order of arguments for substitutions, but the substitutions themselves are implemented. When calling the trace method, the call stack will be displayed in the console (all methods do not return anything, but simply write to the console). It also works at least in Chrome and Opera.

In Opera and Chrome, in addition to those already listed, the following methods are implemented:
count - displays how many times the string on which the method call is located has already been executed. Argument passed a string that will be displayed before the number of calls.
debug - no different than log.

In Opera, there is also a table method, which should build a beautiful table of arguments, but does nothing.
In general, Opera is a bit weird. The results of the discussed functions should be searched for not in the standard console, but in the vast Dragonfly (however, this is logical). And some of them can be found in two places at once: on the tab “Error console” and “Scripts” -> REPL.

Also in Chrome, the console object has a memory property, which is an object with the totalJSHeapSize and usedJSHeapSize properties. However, in Chromium I did not manage to catch these properties with non-zero values.

Source: https://habr.com/ru/post/114483/


All Articles