The 16 JavaScript debugging tips you probably didn’t know

Debug JavaScript faster

Knowing your tools can make a significant difference when it comes to getting things done. Despite JavaScript ‘s reputation as being unmanageable to debug, if you keep a copulate of tricks up your sleeve errors and bugs will take less fourth dimension to resolve.
We ‘ve put together a list of 16 debugging tips that you may not know, but might want to keep in judgment for future time you find yourself needing to debug your JavaScript code !
If you need to find your JavaScript bugs faster, try Raygun Crash Reporting, which will alert you to bugs and give the stack trace.
Most of these tips are for Chrome and Firefox, although many will besides work with other inspectors.

1. debugger

After console.log, debugger is my front-runner quick and dirty debugging instrument. If you place a debugger ; line in your code, Chrome will automatically stop there when executing. You can flush wrap it in conditionals, so it only runs when you need it.

if (thisThing) {    
debugger;}

2. Display objects as a table

sometimes, you have a building 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 benefactor. It makes it easier to see what you ’ rhenium 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 :Display objects as table to help in debugging JavaScript

3. Try all the sizes

While having every one mobile device on your desk would be amazing, it ’ s not feasible in the real global. How about resizing your viewport alternatively ? Chrome provides you with everything you need. Jump into your examiner and click the toggle device mood button. Watch your media queries come to life !Try all the sizes before you start debugging JavaScript

4. How to find your DOM elements quickly

Mark a DOM component in the elements panel and use it in your cabinet. Chrome Inspector keeps the last five elements in its history so that the final marked component displays with $ 0, the second to survive punctuate element $ 1 and then 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 :Find DOM elements quickly

5. Benchmark loops using console.time() and console.timeEnd()

It can be superintendent utilitarian to know precisely how long something has taken to execute, specially when debugging dense 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');

Will end product :Debug slow loops

6. Get the stack trace for a function

You credibly know JavaScript frameworks produce a lot of code – cursorily. You will have a batch of views and be triggering a fortune of events, so finally you will come across a situation where you want to know what caused a particular function call. Since JavaScript is not a very integrated lyric, it can sometimes be hard to get an overview of what happened and when. This is when console.trace ( or merely trace in the console table ) comes in handy to be able to debug JavaScript. Imagine you want to see the entire push-down list trace for the function predict funcZ in the cable car example 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 :Get the stack trace for the function when debugging JavaScript now we can see that func1 called func2, which called func4. Func4 then created an case of Car and then called the officiate car.funcX, and so on. flush though you think you know your script well this can placid be quite handy. Let ’ s say you want to improve your code. Get the trace and your bang-up list of all related functions. Every single one is clickable, and you can nowadays go back and forth between them. It ’ s like a menu just for you .

7. Unminify code as an easy way to debug JavaScript

sometimes you may have an issue in production, and your beginning maps didn ’ thyroxine quite make it to the server. Fear not. Chrome can unminify your Javascript files to a more human-readable format. The code won ’ triiodothyronine be ampere helpful as your veridical code – but at the very least you can see what ’ s happening. Click the { } Pretty Print button below the beginning spectator in the examiner .Unminify code as an easy way to debug JavaScript

8. 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 are :

1. Find the line in your inspector and add a breakpoint
2. Add a debugger in your script

In both of these solutions, you have to navigate manually around in your files to isolate the particular line you want to debug. What ’ south probably less common is to use the comfort. Use debug ( funcName ) in the console table and the handwriting will stop when it reaches the function you passed in. It ’ mho immediate, but the downside is that it doesn ’ t exploit on individual or anonymous functions. otherwise, it ’ south probably the fastest way to find a routine to debug. ( note : there ’ s a function called console.debug which is not the same thing, despite the alike identify. )

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();

type debug ( car.funcY ) in the console and the script will stop in debug manner when it gets a affair call to car.funcY :Debug mode: quick find a function

9. Black box scripts that are NOT relevant

today we often have a few libraries and frameworks on our world wide web apps. Most of them are good tested and relatively bug-free. But, the debugger still steps into all the files that have no relevance for this debug job. The solution is to black box the handwriting you don ’ t need to debug. This could besides include your own scripts. Read more about debugging black box in this article.

10. Find the important things in complex debugging

In more complex debug we sometimes want to output many lines. One thing you can do to keep a better structure of your outputs is to use more comfort functions, for example, console.log, console.debug, console.warn, console.info, console.error and thus on. You can then filter them in your examiner. sometimes this is not very what you want when you need to debug JavaScript. You can get creative and dash your messages, if you so choose. 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 : ‍Find important things quicky to debug JavaScript ‍ In the console.log ( ) you can set % second for a string, % one for integers and % cytosine for custom style. You can probably find better ways to use these styles. If you use a single page model, you might want to have one manner for horizon messages and another for models, collections, controllers and sol on .

11. Watch specific function calls and arguments

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

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

‍ Will end product :Keep an eye on specific functions when debugging JavaScript This is a great way to see which arguments are passed into a serve. ideally, the comfort could tell how many arguments to expect, but it can not. In the above exemplar, func1 expects three arguments, but lone two are passed in. If that ’ s not handled in the code it could lead to a possible hemipterous insect .

12. Quickly access elements in the console

A faster direction to do a querySelector in the console is with the dollar sign. $ ( ‘ css-selector ’ ) will return the beginning match of CSS picker. $ $ ( ‘ css-selector ’ ) will return all of them. If you are using an component more than once, it ’ mho worth saving it as a variable .Quickly access Elements in Inspector

13. 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 piece annoying to open up a new browser window, write newly request objects and then test them.

Sometimes it ’ randomness 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 foliate.

This is how you would edit and resend requests in Firefox. Open up the examiner and go to the Network pill. 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 :A request that has been made twice while debugging JavaSScript

14. Break on node change

The DOM can be a curious thing. Sometimes things transfer and you don ’ triiodothyronine 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 chemical element and pick a demote on setting to use :Break on node change

15. Use page speed services

There are batch of services and tools out there that can be used to audit your page ’ randomness JavaScript and help you to find slowdown or problems. One of those tools is Raygun Real User Monitoring. This can be useful for other reasons beyond locating JavaScript problems — dull load external scripts, unnecessary CSS, outsize images. It can help you to become aware of JavaScript issues that are causing unintentionally long loading times, or failing to execute by rights. You 'll besides be able to measure improvements in JavaScript performance and track them over clock time .Raygun Real User Monitoring helps you discover JavaScript issues

16. Breakpoints everywhere

last, the try and true breakpoint can be a success. Try using breakpoints in different ways for unlike situations .Debugging JavaScript using breakpoints You can click on an chemical element and set a breakpoint, to stop execution when a sealed element gets modified. You can besides go into the Debugger tab key or Sources tab ( depending on your browser ) in your developer tools, and set XHR breakpoints for any specific reservoir to stop on Ajax requests. In the lapp localization, you can besides have it pause your code execution when exceptions occur. You can use these diverse kinds of breakpoints in your browser tools to maximize your chances of finding a microbe while not having to invest time in outside joyride sets.

Conclusion

In drumhead, there are many ways to debug your JavaScript code. We ’ ve listed sixteen of them here. There is besides a helpful article that lists JavaScript debug tools, if you want to start looking at augmenting your browser tools with outside help. Either way, you should be able to use these tips to get your originate debugging your JavaScript code and getting bug-free code fix to deploy and ship !

Want to get 100% visibility on your JavaScript errors?

Raygun surfaces the diagnostic information you need to detect and diagnose JavaScript errors quickly. With confirm for all JavaScript frameworks and implemented with a few lines of code, you can start bashing bugs on your chocolate break.
Take a release trial now and start monitor in minutes. ‍

beginning : https://epicentreconcerts.org
Category : How To

Related Posts

Leave a Reply

Your email address will not be published.