5 effective JavaScript debugging techniques

JavaScript is the web language used by over 90% of websites. Still, it has a reputation of being difficult to debug. JavaScript’s asynchronous nature makes it easy for developers to create complex web applications, but the same attribute makes it challenging to locate errors. Fortunately, knowing the right tools and understanding a few debugging tricks can make it easier to resolve bugs and errors.

Here we have put together a list of practical JavaScript debugging techniques you should keep in mind.

Use debugger

For many JavaScript developers, the debugger is their favorite debugging tool. When writing extensive code with complex logic, experienced programmers place a debugger in the code line that they anticipate will produce an error. When such code is run in Chrome, the Developer Tool will automatically stop when it encounters a debugger keyword.

You can also wrap the debugger in conditions to run them in a particular event like this:

if (thisThing) {
debugger;}
Learn more about debugger keywords here.

Learn to use the console.trace

JavaScript has many frameworks such as Node.js, Vue.js, and React. These frameworks make it easy to produce code quickly. In a project, you will have many views, triggers, and too many events. When working with a framework, most of these events will be hidden in an abstract layer, so it will be challenging to identify what caused a particular function call.

JavaScript is not very structured, and it is hard to get a clear overview of what happened and when. This is why JavaScript developers should use the console.trace method.

Let’s assume in the following code, you want to see the entire stack trace for the function call funcZ:

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

This will be the output at Line 33:

As you can see that the trace clearly indicates func1 called func2, which is further called func4. Then the func4 created an instance of variable Car calling the function car.funcX, and so on. This is a simple script, so it is easier to follow through the flow, but when the code block is a big console.trace method proves to be handy. You can easily trace all related functions to pinpoint the bug.

Use console.time() and console.timeEnd() to benchmark loops 

Not just JavaScript, but loops are trouble makers in every programming language. To create efficient and fast code, developers need to know how long any code segment takes to execute. Slow loops can degrade the performance of the entire JavaScript code. 

But you can benchmark loops to evaluate their performance. Here is a way to set up multiple timers using console.time() and console.timeEnd() methods.

console.time(‘Timer1’);

var items = [];

for(var i = 0; i < 100000; i++){

items.push({index: i});
}

console.timeEnd(‘Timer1’);

The output will be:

As evident, benchmarking loops in JavaScript can help you save time trying to troubleshoot performance issues.

Chrome Developer Tool for responsive test 

As most web applications are accessed through multiple devices, you have to make sure your JavaScript code works on all screen sizes. In an ideal world, developers would have every single device check the compatibility of their code. Unfortunately, in the real world, it is not feasible.

Chrome Developer Tool has the option to resize the viewport to check your code’s performance on any screen size. To use this feature, open the inspector in Chrome and click on the toggle device mode button as highlighted in the image:

Chrome Developer Tool for JavaScript

Using this tool, you can instantly check the media queries, forms, and dynamic code for various screen sizes.

Black box scripts for faster debugging 

Modern web applications use libraries and frameworks that are tested for bugs. But when you run any debugger tool, it will still check and try to debug all files, even those that have no relevance. It substantially increases the cost of debugging and takes longer too.

The solution lies in black-boxing the scripts you don’t need to debug. Fortunately, both Chrome and Firefox provide the option to blacklist scripts that you don’t want to debug.

In Chrome, open the inspector and right-click the JavaScript file you want to blacklist, and choose ‘black box script.’ You can learn more about Chrome Script Black Box here.

In Firefox, go to the debugger tab in the element inspector. Mark the scripts you want to blacklist, then click on the eye at the bottom-left corner. Learn more here.

Conclusion

Debugging is an active responsibility of developers. Its unstructured design makes it challenging to identify and resolve errors with JavaScript. The techniques shared above will help you create JavaScript debugging more efficiently.

Talent500 is one of the best platforms for developers to find remote work opportunities. Join us today to be discovered by the best companies.

Steps for effective debugging of web applications

Web applications are at the forefront of business expansion irrespective of the industry. With the evolution of technology, web applications are becoming complex. Bugs occur all the time – when you build the applications, test after completion, and even post-production. On average, a developer creates 70 bugs per 1000 lines of code. Most web developers spend many more hours debugging rather than creating. 

Around 75% of the development time is spent on debugging, but there are some techniques to reduce the pain significantly. 

This article aims at providing some practical recommendations to help you prevent bugs and shorten the time spent on debugging. 

Use Console.log with variable

JavaScript is part of over 90% of web applications, and one of its most commonly used methods is console.log. Developers often use this method with variables to debug. When you run a web application, the values returned by the variables are specified inside the way in the console. This makes it easier to check the returned values to ensure that they are as expected.

However, it is not an effective debugging method because you cannot see the progress of code execution. If you try to see the progress, you have to insert console.log every few lines. You would not want to use console.log so frequently because then the amount of data shown in the console will be unreadable.

To overcome this challenge and more efficiently use the console.log method for debugging, use a string and the following variable like this:

console.log(‘variable’, variable)

By doing so, you will be able to track the progress of the code and easily debug it.

The ‘debugger’

The debugger is a vital JavaScript concept that can make your life easier when debugging the code. The debugger is a JavaScript keyword that halts the execution of a web application such that the developer can interact with the variables, executing code one step at a time.

Developers can use this keyword for explorative debugging, a paradigm used in manual testing. The debugger is handy for large web applications for which console.log is not enough. You can use the debugger directly from Chrome’s Sources tab or Firefox’s Debugger tab.

<h4>Debugging demonstrations using Debugger keyword</h4>
The solution of 20 * 5 is:
<p id=”test”></p>
<p>If the debugger is turned on the code stops
execution at the start of the debugger</p>
var x = 20;
var y = 5;
var z = x * y;
debugger;
document.getElementById(“test”).innerHTML = z;

As you can see in the code above, the debugger is used before the variable z in the JavaScript part of the code. The code execution stops before displaying the output when you run the code in the Google Chrome browser.

This is a simple example of how developers can use the debugger keyword to make debugging more efficient.

React developer tools

If you are working with a web application built in React, you can utilize React Developer Tools suite for debugging. These tools allow you to easily view the React tree structure, breaking down the project code by the states and the props in the component. It comes in handy when hundreds and even thousands of parts are in a project. Going through thousands of lines of code to find a component is tedious; this debugging tool simplifies the process.

You can install React Developer Tools as an add-on to the Google Chrome Developer Tools debugging module. It is a free and open-source extension that provides a powerful ‘Select an element’ functionality to inspect any project element if you are unaware of the whole project. It also helps you quickly discover components in a large project. If your project uses Vue.js, there is another excellent extension, Vue.js devtools, that you can use for similar debugging features.

Explicitly document all external dependencies

Every project should have a README file within its source control system. A quality of a good developer is that they include every bit of information with the applications they develop to make it easier for other developers and stakeholders to use the application.

A README file should document all external systems, resources, or databases necessary for the web application to function correctly. It should also explicitly list what resources are optional and how to handle external resources.

All significant web projects have a README.md file that keeps track of what bugs occurred and changes made to the project. It is also a way to tell your company what improvements you made to the project through debugging.

Conclusion 

Follow these recommendations when you are building a new web application, and it will become a lot easier to debug errors. These debugging techniques will reduce the time and cost spent troubleshooting production bugs and crashes.

Top Indian talent finds career re-defining opportunities with Talent500. Join us today and be part of an elite pool of developers.