Commands for working with JavaScript-console in browsers and increase programmer productivity

If you are engaged in web programming, it means that you do not need to talk about how important debugging is in your work. Often, external libraries are used to write data to logs, to format them or display them on screen, without taking into account the fact that programmers have JavaScript commands for working with consoles that are built into browsers. And these consoles possess much more serious capabilities than it might seem at first glance.

image

Perhaps the first thing that comes to mind when the word “console” is the console.log() command. However, she is just one of many such teams. The material, the translation of which we are publishing today, is devoted to the peculiarities of working with the JavaScript console.

What is a console?


The JavaScript console is a mechanism integrated into modern browsers that supports embedded development tools in an interface that resembles a command line. Using the console, the developer can do the following:


In general, the console allows the developer to write JavaScript code directly in the browser, monitor what is happening on the pages, and manage these processes.

Methods console.log, console.error, console.warn and console.info


Probably the most commonly used methods when working with the console are console.log() , console.error() , console.warn() and console.info() . One or more parameters can be passed to these methods. The system calculates the value of each of them and combines all the results into a string, parts of which are separated by spaces. In the case of objects or arrays, these commands allow you to display them in a form that allows you to view their contents. Here's what it looks like.


Using various commands to display data in the console

Method console.group


The console.group() method allows you to collect a series of console.log() calls (as well as other similar methods) into groups, the contents of which can be collapsed and expanded. Using this method is very simple: after calling console.group() (or after console.groupCollapsed() , if you want to output the group immediately in collapsed form) you need to put all the console.log() calls that need to be grouped. Then, at the end of the set of commands you want to group, you need to put the command console.groupEnd() . Consider an example.

 function doSomething(obj){   console.group('doSomething Profile');   const _data = new Date();   console.log('evaluating data: ', _data);   const _fullName = `${obj.firstName} ${obj.lastName}`;   console.log('fullName: ', _fullName);   const _id = Math.random(1);   console.log('id: ', _id);   console.groupEnd(); } doSomething({"firstName":"Riccardo", "lastName":"Canella"}); 

After executing this code snippet, the following will get to the console.


Grouping data in the console using the console.group () method

Console.table method


After I learned about the existence of the console.table() method, my life changed forever. For example, using the usual console.log() command when outputting JSON code or large JSON arrays is a nightmare. The console.table() method allows you to display complex data structures within nice tables, columns of which can be given names, passing them as parameters (not all browsers support console.table() ). Here is an example of working with this team.

 const typeOfConsole = [   {name:'log', type:'standard'},   {name:'info', type:'standard'},   {name:'table', type:'wow'} ]; console.table(typeOfConsole); const mySocial = {   facebook: true,   linkedin: true,   flickr: true,   instagram: true,   VKontaktebadoo: false }; console.table(mySocial, ["Socials", "I'v an account"]); 

That turned out, and it looks great, and can facilitate debugging.


Tabular display of output data using console.table ()

Methods console.count, console.time and console.timeEnd


The methods console.count() , console.time() and console.timeEnd() can be called something of a Swiss knife for a developer who debugs applications. So, the console.count() method allows you to count the number of your own calls and output it to the console with a given label. The console.time() method allows you to start a named timer (the name is passed to it as a parameter, up to 10,000 timers can be present on one page). To stop a specific timer, use the console.timeEnd() command with a timer label passed as a parameter. It stops the timer and displays the time of its work in the console. Here is how to use these methods.

 console.time('total'); console.time('init arr'); const arr = new Array(20); console.timeEnd('init arr'); for(var i = 0; i < arr.length; i++){   arr[i] = new Object();   const _type = (i % 2 === 0) ? 'even' : 'odd';   console.count(_type+'added'); } console.timeEnd('total'); 

And here is the result of the operation of this code in the console.


Using the methods console.count (), console.time () and console.timeEnd ()

Methods console.trace and console.assert


The console.trace() and console.assert() methods will allow you to display information about the stack from the place they are called. Imagine that you are developing a JS library and want to inform the user about where the error occurred. In this case, these methods can be very useful. The console.assert() method is similar to console.trace() , the difference between the two is that console.assert() will output data only if the condition passed to it is not met. Here's how to work with these methods.

 function lesserThan(a,b){   console.assert(a<b, {       "message":"a is not lesser than b",       "a": a,       "b": b   }); } lesserThan(6,5); console.trace("End"); 

It's easy to see that the output generated by this code snippet looks just like something similar in React (or in any other library) when the framework reports an exception.


The result of using the commands console.assert () and console.trace ()

Commands for working with the console and production code


Commands for working with the console are needed during the development and debugging of applications. This means that when the time comes for product release, these commands will have to be removed from the code. You can simply forget about this and, some time after the production version of the project is assembled, you should notice that the program writes something to the console when there is no need for it. It is not necessary to load computers with unnecessary work, even if it seems to be insignificant, as outputting data to the console. At the same time, given that the commands for working with the console can be useful during the finalization of the application, it is best not to remove them from the program source code for good, but to remove them only from its production version. Here we will come to the aid of funds to build projects. So, I constantly use Webpack, both at work and in my own projects. This tool allows you to remove all unnecessary commands for working with the console (it is able to distinguish them from other teams) from production assemblies using the uglifyjs-webpack-plugin .

 const UglifyJsPlugin = require('uglifyjs-webpack-plugin') var debug = process.env.NODE_ENV !== "production"; ..... optimization: {       minimizer: !debug ? [           new UglifyJsPlugin({               //                 uglifyOptions: {                   //                     comments: false,                   compress: {                      //                        warnings: false,                      //                            drop_console: true                   },               }          })] : [] } 

This configuration is very simple, but it facilitates the daily work of the programmer and eliminates the problem of forgotten commands to work with the console.

Results


In this article, we talked about some useful commands for working with the console. They allow, using tools that are part of modern browsers, to solve many problems that accompany the development and debugging of client-side JavaScript applications.

Dear readers! What commands for working with JavaScript-console do you use?

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


All Articles