We all have been using console.log(), but many more options are available out there.Let us see them now
The most useful type beyond log is console.table()
console.table()
- Takes in JSON or an array and prints in table format
- Very handy while visualising json objects and arrays
Syntax:
console.table({ "id":"1", "key":"value", "count":2 });
console.table([
{
id: "1",
key: "value",
count: 2,
},
{
id: "2",
key: "value2",
count: 22,
},
{
id: "3",
key: "value3",
count: 5,
},
]);
The next useful method is error
console.error()
- useful to differentiate errors from output logs while debugging
- red in color
Next one, useful while calculating runnning times is time method
Time(time,timeLog,timeEnd)
- To understand this, let us assume scenario of a stopwatch
- console.time()
- equivalent to stopwatch start
- console.timeLog()
- like stopwatch lap/split
console.timeEnd()
stopwatch end
It works on basis of label. Label should be the same to get expected output
console.time("ForLoop"); // "ForLoop" is label here for (let i = 0; i < 5; i++) { console.timeLog('ForLoop'); } console.timeEnd("ForLoop");
Next one is warning
console.warn();
- yellow color
- For warnings
console.assert()
console.assert(assert_statement,message)
- evaluate assertion statement and if it is false displays the message
if(3!=2){
console.error({ msg1: "msg1", msg2: "msg2" });
}
-----------same as---------
console.assert(3 === 2, { msg1: "msg1", msg2: "msg2" });
Other way
console.assert(assert_statement,message,args)
console.assert(false, "%d nd type for %s ",2,"console.assert() method");
Useful method for counting
console.count() works on basis of label
console.count(label)
for (let i = 0; i < 3; i++) { console.count("label"); console.count(); console.count(i); } // output for console.count() console.count("label") console.count(i) default: 1 label: 1 0: 1 default: 2 label: 2 1: 1 default: 3 label: 3 2: 1
- console.count()
- if no label is mentioned it will consider default as label
- The problem with default is it will continue the count like this
- console.count()
console.countReset(label)
resets count of specified label to 0
I mentioned only few methods which I think are more helpful.To check all the available methods refer here