How to debug JavaScript like a pro.

JavaScript , 1 Comment

First of all, I want to tell you, yes there are good and bad ways to console.log in JavaScript that can make your life easier as a JavaScript developer. So let’s get started on how to debug javascript?

Let’s imagine we have 3 objects to log like below.

const foo = { name: 'tom',   age: 30, nervous: false };
const bar = { name: 'dick',  age: 40, nervous: false };
const baz = { name: 'harry', age: 50, nervous: true };

Bad Code 💩

console.log(foo);
console.log(bar);
console.log(baz);

In the above approach, the problem is we don’t have the variables name to see which one is which? Inside console.

Normal/basic console.log

Good Code ✅

But there is a trick called Computed Property Names

console.log({ foo, bar, baz });

It reduces the code but also shows exactly which variable defines the data.

  • one line of code.
  • one console log.
  • and all the specified information.

Computed Property Names console.log output

But guess what? There are already too many console logs and your log is important that you want to make it stand out. So, you can also add some custom CSS styles to your logs by using a percent sign (%).

console.log('%c Here we go!!!', 'color: yellow; font-weight: bold;')

Colored and bold console.log output

Now we get that yellow and bold console log.

One more important thing just to use the console.table() when you have an array of objects. This is very useful when you have to print arrays in the console.

// Console.table(...)
console.table([foo, bar, baz])
console.table() output

Tracking time in console, let’s imagine you want to know how much time your loop/code is actually taking.

console.time('loopTime')

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

console.timeEnd('loopTime')
console.time() output

I hope you are now a debugging expert. If you find this article helpful share it.

One thought on “How to debug JavaScript like a pro.

Leave a Reply

Your email address will not be published. Required fields are marked *