DEV Community

Cover image for Writing Better JavaScript [console.log]
Bek Brace
Bek Brace

Posted on

Writing Better JavaScript [console.log]

This is a summary for a video I've watched recently on how to avoid writing bad JavaScript by writing a better code.

console.log "stuff" !

If you have different variables :
const foo = {name: 'tom', age:30, nervous: false};
const bar = {name: 'tim', age:32, nervous: true};
const baz = {name: 'jin', age:34, nervous: false};

Bad Code :
So, the obvious way to log these variables is to do it one after the other

console.log(foo);
console.log(bar);
console.log(baz);
But the main problem is that we don't know the name of the variables when it gets logged.
But there is a trick we can use called "Computer Property Names" where we add the variables to an object.

Good Code:
//1 Computed Property Names
console.log({foo, bar, baz});
Not that this only reduces the code footprint, but it also tells us exactly which variable define this data.

Maybe this data is important, so we want to make it stand out with some custom CSS styling
You can substitute data and also CSS styles by using a percent sign, so we will add %c and then have the second argument which is our CSS style.

console.log('%c My Friends')

//2 console.table(...)

console.table([foo, bar, baz]);

One thing you might have noticed in the console is that the objects all share common properties so maybe we can display those as a table , this is really useful when you have an array of objects , just do console.table with the array

//3 console.time
If you're benchmarking performane, you can actually keep track of the console, we'll first define our timer and we'll give it a name of looper :

let i = 0;
while (i < 100000) {i++} ;

We will have a while loop for a million iteration, and when that is done we will run console.timeEnd
console.timeEnd('looper')

Keeping Track of time is good, but what if you need to know where a console.log originated from ?

// 4 Stack Trace Logs
Let us imagine that we have a function that deletes items from our database, and we want to make sure that we don't call it twice, accidently

const deleteMe = () => console.trace('database deleted!')
deleteMe()

You can add a console.trace function and it will give you a stack trace for where it was called what defined it.
If we run this code, we get consolelog.js that tells us the function was defined on line 35 and so on

The End

Top comments (0)