Handy Tips on Using console.log()

栏目: IT技术 · 发布时间: 4年前

内容简介:This post suggests 5 useful tips that will make you even more productive when usingWhen logging many variables, you may find difficult to understand to what log corresponds to a specific variable.

console.log(message) usage is simple: the argument message is logged to console.

console.log('My message');
// logs "My message"

const myVar = 12;
console.log(myVar);
// logs 12

This post suggests 5 useful tips that will make you even more productive when using console.log() .

1. Naming logged variables

When logging many variables, you may find difficult to understand to what log corresponds to a specific variable.

Let’s log some variables:

function sum(a, b) {
  console.log(b);  return a + b;
}

sum(1, 2);
sum(4, 5);

When the above code is executed, you’ll see just a series of numbers:

Handy Tips on Using console.log()

To make an association between the logged value and variable, wrap the variable into a pair of curly braces { b } :

function sum(a, b) {
  console.log({ b });  return a + b;
}

sum(1, 2);
sum(4, 5);

Now looking at the console, it’s easy to understand that exactly variable b is being logged:

Handy Tips on Using console.log()

2. Advanced formatting

The most common way to log something to console is to simply call console.log() with one argument:

console.log('My message');
// logs "My message"

Sometimes you might want a message containing multiple variables. Fortunately, console.log() can format the string in a sprintf() way using specifiers like %s , %i , etc.

For example, let’s format a message containing a string and integer:

const user = 'john_smith';
const attempts = 5;

console.log('%s failed to login %i times', user, attempts);
// logs "john_smith failed to login 5 times"

%s and %i are replaced with values of user and attempts . The specifier %s is converted to a string, while %i is converted to a number.

Here’s a list of available specifiers:

Specifier Purpose
%s Element is converted to a string
%d or %i Element is converted to an integer
%f Element is converted to a float
%o Element is displayed with optimally useful formatting
%O Element is displayed with generic JavaScript object formatting
%c Applies provided CSS

3. Log with style

Browser console lets you apply styles to the logged message.

You can do this by using the %c specifier with the corresponding CSS styles. For example, let’s a log message with increased font size and font weight:

console.log('%c Big message', 'font-size: 36px; font-weight: bold');

The specifier %c applies the CSS styles 'font-size: 36px; font-weight: bold' .

Here’s how the log with applied styles looks in Chrome console:

Handy Tips on Using console.log()

4. Interactive logs

How the console styles the logs depends on the host implementation. Browsers like Chrome and Firefox offer interactive logs of objects and arrays, while Node console outputs logs as text.

Let’s see how Chrome logs the plain objects, arrays and DOM trees. You can interact with these elements by expanding and collapsing.

4.1 Objects

const myObject = {
  name: 'John Smith',
  profession: 'agent'
};

console.log(myObject);

In Chrome console the log of myObject looks like:

Handy Tips on Using console.log()

You can expand and collapse the list of object properties. As well you can see the prototype of the object.

4.2 Arrays

const characters = ['Neo', 'Morpheus', 'John Smith'];

console.log(characters);

Chrome logs the characters array as follows:

Handy Tips on Using console.log()

4.3 DOM trees

You can interact directly with a DOM element that is displayed in the console.

console.log(document.getElementById('root'));

In Chrome console, the DOM element can be expanded and its content can be explored in full:

Handy Tips on Using console.log()

4.4 Interactive log inside messages

The %o specifier (which associates the right log formatting for the value) can insert arrays, objects, DOM elements, and regular text into a textual message, without losing the interactivity.

The following snippet logs a message containing an object:

const myObject = {
  name: 'John Smith',
  profession: 'agent'
};

console.log('Neo, be aware of %o', myObject);

Looking at the console, the myObject array wasn’t converted into a string, but rather is kept interactive.

Handy Tips on Using console.log()

5. Logging big objects in Node console

The logs in Node are output as plain text. However, console.log() in Node doesn’t display objects with a deep level of nesting. Objects at level 3 are shown as [Object] .

For example, let’s log the following object:

const myObject = {
  propA: {
    propB: {
      propC: {
        propD: 'hello'
      }
    }
  }
};

console.log(myObject);

When running the above script, the object of propC is logged as [Object] :

Handy Tips on Using console.log()

To see the full object structure, I log the JSON representation of the object using JSON.stringify() :

const myObject = {
  propA: {
    propB: {
      propC: {
        propD: 'hello'
      }
    }
  }
};

console.log(JSON.stringify(myObject, null, 2));

JSON.stringify(myObject, null, 2) returns a JSON representation of the object. The third argument 2 sets the indent size in spaces.

Now the object is logged fully and nicely formatted:

Handy Tips on Using console.log()

Hopefully, the 5 tips presented above will make your logging experience in JavaScript more productive. What loggin tips do you know? Please write a comment below!


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

新内容创业:我这样打造爆款IP

新内容创业:我这样打造爆款IP

南立新、曲琳 / 机械工业出版社 / 2016-5-10 / 39.00

这是个内容创业爆棚的时代,在采访几十家内容创业公司,与一线最优秀的创业者独家对话之后,作者写作了这本书,其中包括对这个行业的真诚感触,以及希望沉淀下来的体系化思考。 本书共分三个部分讲述了爆红大号的内容创业模式和方法。其中第一部分,讲述了新的生产方式,即内容形态发展的现状--正在被塑造;第二部分,讲述了新的盈利探索,即从贩卖产品到贩卖内容的转变,该部分以多个案例进行佐证,内容翔实;第三部分,......一起来看看 《新内容创业:我这样打造爆款IP》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

html转js在线工具
html转js在线工具

html转js在线工具