Javascript Debugging Best Practices

GrooTech
Bits and Pieces
Published in
7 min readAug 10, 2020

--

Debugging is not easy. It’s a skill that every developer needs to master. Developers are always prone to errors when writing code. We cannot totally eliminate bugs but we can learn how to tackle them in a smart way.

In this article, we will look at the ways we can debug a Javascript code. The good thing is that all modern browsers are shipped with a built-in JavaScript debugger.

Best Practices

It’s better to prevent our code from becoming prone to bugs. A single code/logic can be written in multiple ways. How well programmers and beginners write their code comes into play here. We also need to have well-structured code which will help us in debugging later on.

Beautify to Debug

We may need to debug in production. But in case we have our code minified or unindented, we can also un-minify code into a more readable format.

The code won’t be as helpful as our real code but at least we will know what’s happening. Below we can see a button available in Chrome to beautify our code in readable format.

Debugging Methods

Console Method

We can use a console API for debugging the JavaScript code. There are various options for the console API.

  • console.log(): We can use console.log() to print the any values string or object in the debugger window of browser.
function add(num1, num2) {return num1 + num2}let num1 = 5, num2 = 6;let result = add(num1, num2);console.log("%d + %d = %d", num1, num2, result);console.info("%d + %d = %d", num1, num2, result);console.warn("%d + %d = %d", num1, num2, result);console.error("%d + %d = %d", num1, num2, result);
  • console.table(data, obj): This function takes one mandatory argument data, which must be an array or an object and one additional optional parameter columns, array of string.It prints data as a table.
function Band(firstName, lastName, roll) {this.firstName = firstName;this.lastName = lastName;this.roll = roll;}var Zack = new Band("Zack", "Wyld", 1);var Ozzy = new Band("Ozzy", "Osbourne", 2);var Ronie = new Band("Ronie", "Dio", 3);console.table([zack,ozzy,ronie]);

We can use the optional columns parameter to select a subset of columns to display:

console.table([Zack,Ozzy,Ronie],["firstName","lastName"]);
  • console.trace(): This will show you the call path to reach the point at which you called console.trace()
function func1() {func2();}function func2() {func3();}function func3() {console.trace();}func1();
  • console.assert(expression,object): This method writes an error message to the console if the assertion is false. If the assertion is true, nothing happens.
function isOddNumber(num1) {let result = num1 % 2 !== 0console.assert(result,{ number: num1, errorMsg: "this number is even" });return result;}isOddNumber(6)

Using a Debugger

Debugger is a reserved keyword in EcmaScript since ES5. When we place the debugger inside our code this halts the execution of Javascript.

If we have our inspector tool open, it can only take its effect and we can start debugging.

3. function startCount() {4.    debugger5.    timeOut = setTimeout('Decrement()', 60);6. }7.

Breakpoints

There are a number of ways we can use to debug our code. At each breakpoint, JavaScript will halt its execution, and let us examine values inside our code.

Unconditional Breakpoints

When we want to pause the code of execution when we reach its line is the unconditional breakpoint. We can set an unconditional breakpoint by clicking on the line number to the left.

The line number is highlighted with a red dot.

Here is the simple code example above where we have set our unconditional breakpoint to line number 5. And we can further drill into our debugging process ahead from that point.

Using a Breakpoint List

When we added a breakpoint, the breakpoint list in the right shows the filename and line number of each breakpoint.

The example can be seen in the screenshot below with red border:

Adding Logpoints

There are times where we want to view the value of a variable but we don’t want to pause execution. For this approach we can use logpoints.

Log Points help us by printing a message to the Console without pausing the execution of the code. When we set a logpoint we can see a red bubble with a small caret.

We can also take a look at our log point in the right panel of breakpoints as well. Hitting on a logpoint, the message we defined will be printed right into the console.

Output we get:

Unsetting Breakpoints

We can unset again in the case if we have it set already. Which means simply we can remove the breakpoint as well.

We can right click on the number and click on remove breakpoint options.

This is a total time saving trick when we will be able to access the values we want to identify to that point of execution easily. It’s also shown in the screenshot above.

Using Watches

Watch is just like observing any expression we would like to watch in our code. We can use a watch expression with the inspector tool to dig down into finding bugs.

We can add the variables to watch by clicking on the watch icon in the watch panel and adding the variable name to it.

Here in the example we are watching two variables, one is minute and the other second. We are able to evaluate any expression that we want into our code using watches.

Using Call Stack

It goes bottom up approach. If we enabled call stack in the browser with a breakpoint, it would give us the function call one after another. The function executed at first would stay in the bottom and preceding it stays at the top.

Let’s take a look into the code for example. Here we have three main calls stacking one after another. The one at the bottom executes first.

Debugging Tools

Rookout

Rookout is a debugging platform that allows developers to set rules and conditions for when or how a breakpoint is triggered. To see it in action, you can try their sandbox environment.

This remote debugging tool gives us clear insight into our application without the need to restart, redeploy or write code. It’s easy to debug at any stage whether cloud, local, dev or production, monolithic or Microservices including Serverless architecture.

NodeJS Inspector

Developers who are writing code for the backend with JS have a GUI-based debugger for Node as well. It can also be activated writing the command into our terminal:

npm install -g node-inspectorpath:\>node-inspector --web-port=5500

Using a Code Editor

There are lot of great text editors out there and we can find some extensions useful to debug our code. Some of the well-known editors we can use are Sublime, Visual Studio, Webstorm, Vim, etc.

Framework Debugging Tools (Angular, React, Vue)

For the framework enthusiast, there are browser add-ons/extensions for debugging. The major and popular frameworks like React, Vue and Angular have their own extensions which can be installed for debugging as well.

JSON Formatter and Validator

JSON is sometimes difficult to read. So we have JSON formatter and validator to work with JSON data. The first helps us format it into human readable format, whereas validator helps us check whether our JSON is valid or not.

“use strict” mode

Introduced in ECMAScript5, this is the way to restrict certain variant in our Javascript code. Browsers that does not support strict mode will execute the code in a different way.

Strict mode changes both runtime behavior and syntax as well. We generally apply strict mode to the entire script and also to individual function, whereas it doesn’t apply to a block of statements closed in {} braces.

Conclusion

There are also many other ways that we can use to debug our code. We’ve just covered some of them here. With these ideas and tricks, you should now be comfortable enough to start debugging your code and start shipping out bug-free code.

Share & Manage Reusable React Components with Bit

Use Bit (Github) to share, document, and manage reusable components from different projects. It’s a great way to increase code reuse, speed up development, and build apps that scale.

Example: exploring shared React components on Bit.dev

--

--