Top 23 JavaScript Debugging Tips Like a Professional

Knowing your tools can make a significant difference when it comes to getting things done. Despite JavaScript’s reputation as being difficult to debug, if you keep a couple of tricks up your sleeve errors and bugs will take less time to resolve.

So hopefully now, I can give you some tips which you didn’t know before, and which will make you a PRO debugger. We’ve put together a list of 23 debugging tips that you may not know, but might want to keep in mind for next time you find yourself needing to debug your JavaScript code!

1. ‘debugger;’

After console.log, ‘debugger;’ is my favorite quick and dirty debugging tool. Once it’s in your code, Chrome will automatically stop there when executing. You can even wrap it in conditionals, so it only runs when you need it.

if (thisThing) {
    debugger;
}

2. console.trace()

If you want to know where the log is being prompted from use console.trace() to get the stack trace with the logged data.

3. console.time() && console.timeEnd()

If you are trying to find a sneaky performance issue, start counting time with console.time() and print with console.timeEnd().

It can be super useful to know exactly how long something has taken to execute, especially when debugging slow loops. You can even set up multiple timers by assigning a label to the method. Let’s see how it works:

console.time('Timer1');

var items = [];

for(var i = 0; i < 100000; i++){
   items.push({index: i});
}

console.timeEnd('Timer1');

This has produced the following result:

This is image title

4. console.memory

If your performance issue is even trickier, and you are looking for a sneaky memory leak, you might like to try and utilize console.memory (property, not a function) to check out your heap size status.

5. console.profile(‘profileName’) & console.profileEnd(‘profileName’)

This is not standard, but is widely supported. You can start and end a browser performance tool - performance profile from the code using console.profile(‘profileName’) and then console.profileEnd(‘profileName’). This will help you profile EXACTLY what you want, and prevents you from having to be mouse-click, timing dependent.

6. console.count(“STUFF I COUNT”)

In a case of recurring function or code, you can use console.count(‘?’) to keep count of how many times your code is read.

7. console.assert(false, “Log me!”)**

Yes, conditional logging without wrapping your logs with if-else :)

You can use console.assert(condition, msg) to log something when the condition is falsy.

*disclaimer — in Node.js this will throw Assertion Error!

8. console.group(‘group’) & console.groupEnd(‘group’)

After writing so many logs, you might want to organize them. A small and useful tool for that is the console.group() & console.groupEnd(). Using console group, your console logs are grouped together, while each grouping creates another level in the hierarchy. Calling groupEnd reduces one.

9 console.clear()

Well, having written so many logs, it’s now time to clear your console a little.

10 console.table()

Saving the best for last, this is a true gem in my opinion! You can actually print a very nice table with the objects you log using the console.table()

11. String substitutions

When logging, you can incorporate variables using string substitutions. These references should be types (%s = string, %i = integer, %o = object, %f = float).

12. Display objects as a table

Sometimes, you have a complex set of objects that you want to view. You can either console.log them and scroll through the list, or break out the console.table helper. Makes it easier to see what you’re dealing with!

var animals = [
    { animal: 'Horse', name: 'Henry', age: 43 },
    { animal: 'Dog', name: 'Fred', age: 13 },
    { animal: 'Cat', name: 'Frodo', age: 18 }
];
 
console.table(animals);

Will output:

This is image title

13. Try all the sizes

While having every single mobile device on your desk would be awesome, it’s not feasible in the real world. How about resizing your viewport instead? Chrome provides you with everything you need. Jump into your inspector and click the ‘toggle device mode’ button. Watch your media queries come to life!

This is image title

14. How to find your DOM elements quickly

Mark a DOM element in the elements panel and use it in your console. Chrome Inspector keeps the last five elements in its history so that the final marked element displays with $0, the second to last marked element $1 and so on.

If you mark following items in order ‘item-4′, ‘item-3’, ‘item-2’, ‘item-1’, ‘item-0’ then you can access the DOM nodes like this in the console:

This is image title

15. Get the stack trace for a function

You probably know JavaScript frameworks, produce a lot of code – quickly.

It creates views and triggers events, so eventually you’ll want to know what caused the function call.

Since JavaScript is not a very structured language, it can sometimes be hard to get an overview of what happened and when. This is when console.trace (or just trace in the console) comes handy to be able to debug JavaScript.

Imagine you want to see the entire stack trace for the function call funcZ in the car instance on line 33:

var car;
var func1 = function() {
	func2();
}

var func2 = function() {
	func4();
}
var func3 = function() {
}

var func4 = function() {
	car = new Car();
	car.funcX();
}
var Car = function() {
	this.brand = ‘volvo’;
	this.color = ‘red’;
	this.funcX = function() {
		this.funcY();
	}

	this.funcY = function() {
		this.funcZ();
	}

	this.funcZ = function() {
		console.trace(‘trace car’)
	}
}
func1();
var car; 
var func1 = function() {
	func2();
} 
var func2 = function() {
	func4();
}
var func3 = function() {
} 
var func4 = function() {
	car = new Car();
	car.funcX();
}
var Car = function() {
	this.brand = ‘volvo’;
	this.color = ‘red’;
	this.funcX = function() {
		this.funcY();
	}
	this.funcY = function() {
		this.funcZ();
	}
 	this.funcZ = function() {
		console.trace(‘trace car’)
	}
} 
func1();

Line 33 will output:

This is image title

Now we can see that func1 called **func2, **which called func4. Func4 thencreated an instance of Car and then called the function car.funcX, and so on.

Even though you think you know your script well this can still be quite handy. Let’s say you want to improve your code. Get the trace and your great list of all related functions. Every single one is clickable, and you can now go back and forth between them. It’s like a menu just for you.

This is image title

16. Unminify code as an easy way to debug JavaScript

Sometimes you may have an issue in production, and your source maps didn’t quite make it to the server. Fear not. Chrome can unminify your Javascript files to a more human-readable format. The code won’t be as helpful as your real code – but at the very least you can see what’s happening. Click the {} Pretty Print button below the source viewer in the inspector.

This is image title

17. Quick-find a function to debug

Let’s say you want to set a breakpoint in a function.

The two most common ways to do that is:

Find the line in your inspector and add a breakpoint

Add a debugger in your script

In both of these solutions, you have to click around in your files to find the particular line you want to debug

What’s probably less common is to use the console. Use debug(funcName) in the console and the script will stop when it reaches the function you passed in.

It’s quick, but the downside is it doesn’t work on private or anonymous functions. But if that’s not the case, it’s probably the fastest way to find a function to debug. (Note: there’s a function called console.debug which is not the same thing.)

var func1 = function() {
	func2();
};

var Car = function() {
	this.funcX = function() {
		this.funcY();
	}

	this.funcY = function() {
		this.funcZ();
	}
}

var car = new Car();

Type debug(car.funcY) in the console and the script will stop in debug mode when it gets a function call to car.funcY:

This is image title

18.  Black box scripts that are NOT relevant

Today we often have a few libraries and frameworks on our web apps. Most of them are well tested and relatively bug-free. But, the debugger still steps into all the files that have no relevance for this debugging task. The solution is to black box the script you don’t need to debug. This could also include your own scripts.

19. Find the important things in complex debugging

In more complex debugging we sometimes want to output many lines. One thing you can do to keep a better structure of your outputs is to use more console functions, for example, Console.log, console.debug, console.warn, console.info, console.error and so on. You can then filter them in your inspector. But sometimes this is not really what you want when you need to debug JavaScript. It’s now that YOU can get creative and style your messages. Use CSS and make your own structured console messages when you want to debug JavaScript:

console.todo = function(msg) {
	console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}

console.important = function(msg) {
	console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}

console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);

Will output:

This is image title

For example:

In the console.log() you can set %s for a string, %i for integers and %c for custom style. You can probably find better ways to use this. If you use a single page framework, you maybe want to have one style for view message and another for models, collections, controllers and so on. Maybe also name the shorter like wlog, clog and mlog use your imagination!

20. Watch specific function calls and its arguments

In the Chrome console, you can keep an eye on specific functions. Every time the function is called, it will be logged with the values that it was passed in.

var func1 = function(x, y, z) {
//....
};

Will output:

This is image title

This is a great way to see which arguments are passed into a function. But I must say it would be good if the console could tell how many arguments to expect. In the above example, func1 expect 3 arguments, but only 2 is passed in. If that’s not handled in the code it could lead to a possible bug.

21. Quickly access elements in the console

A faster way to do a querySelector in the console is with the dollar sign. $(‘css-selector’) will return the first match of CSS selector. $$(‘css-selector’) will return all of them. If you are using an element more than once, it’s worth saving it as a variable.

This is image title

22. Postman is great (but Firefox is faster)

Many developers are using Postman to play around with ajax requests. Postman is excellent, but it can be a bit annoying to open up a new browser window, write new request objects and then test them.

Sometimes it’s easier to use your browser.

When you do, you no longer need to worry about authentication cookies if you are sending to a password-secure page. This is how you would edit and resend requests in Firefox.

Open up the inspector and go to the network tab. Right-click on the desired request and choose Edit and Resend. Now you can change anything you want. Change the header and edit your parameters and hit resend.

Below I present a request twice with different properties:

This is image title

23. Break on node change

The DOM can be a funny thing. Sometimes things change and you don’t know why. However, when you need to debug JavaScript, Chrome lets you pause when a DOM element changes. You can even monitor its attributes. In Chrome Inspector, right click on the element and pick a break on setting to use:

This is image title

Hopefully, these tips make you’re debugging in your JavaScript bit more productive, and even a little fun! Thank you for reading! Please share if you liked it!

#JavaScript #Debugging #Tips #JavaScriptTips #Tutorial

Top 23 JavaScript Debugging Tips Like a Professional
4 Likes70.30 GEEK