0

Many ways to use `console`

A wide range of methods are provided for the Console object

console.log(console);

console {debug: ƒ, error: ƒ, info: ƒ, log: ƒ, warn: ƒ, …}
memory: (...)
debug: ƒ debug()
error: ƒ error()
info: ƒ info()
log: ƒ log()
warn: ƒ warn()
dir: ƒ dir()
dirxml: ƒ dirxml()
table: ƒ table()
trace: ƒ trace()
group: ƒ group()
groupCollapsed: ƒ groupCollapsed()
groupEnd: ƒ groupEnd()
clear: ƒ clear()
count: ƒ count()
countReset: ƒ countReset()
assert: ƒ assert()
profile: ƒ profile()
profileEnd: ƒ profileEnd()
time: ƒ time()
timeLog: ƒ timeLog()
timeEnd: ƒ timeEnd()
timeStamp: ƒ timeStamp()
context: ƒ context()
Symbol(Symbol.toStringTag): "Object"
get memory: ƒ ()
set memory: ƒ ()
__proto__: Object

Even we have these amount of methods, I still feel that something is lurking in the shadows besides the log().

So this time I will reveal some hidden methods

Objective:

To have a better understanding about how to use methods of console

Assert

If the value of the first argument is false, output is error.

const method = (num) => {
    console.assert(num > 0 , num + ' is NG.');
}

method(1);
method(0);
method(-1);

clear()

Clear the console

console.log('hoge');
console.log('hoge');
console.clear();
console.log('fuga');
console.log('fuga');

count()

Output is how many time the function is called

const method = () => {
    console.count('counter');
}

method();
method();
method();

error()

An error is output

console.error('error');

group() / groupEnd()

Start with an indent, closes with an indent

console.group('Indent1');
console.log('hoge');
console.log('hoge');
console.group('Indent2');
console.log('fuga');
console.log('fuga');
console.groupEnd();
console.log('hoge');
console.log('hoge');
console.groupEnd();

table()

The log is output in a table form:

const ary = [100,200,300,400];
const obj = {
    'a':100 ,
    "b":200 ,
    "c":300 ,
    'd':400
};
console.table(ary);
console.table(obj);

warn()

Output a warning

console.warn('warn');

Conclusion

What do you think?

You can see that the Console object is not just for outputting logs. Something like table() or group() seems to be more convenient than log() depending on how you use it.

We hope you find it helpful to master the console


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí