Debugging is a vital part of identifying why your application is misbehaving. We feel great satisfaction once we find the bug in our code and fix it.
No matter how skilled we get as developers, we still have to spend countless hours fixing bugs in our code. Thus, we should work on improving our debugging skills. If you work with JavaScript, you know it is not always cooperative. Fortunately, several JS debugging tools are accessible, usually making troubleshooting straightforward.
This article will discuss how we can debug JavaScript using the simple and efficient tools in Visual Studio Code and Google Chrome.
A breakpoint is where a line of code causes the debugger to pause JavaScript execution. We can examine current variables and run commands in the console while the code is paused. To put it another way, we can debug it. A list of breakpoints is always available in the right panel of Chrome DevTools. This is useful when we have a lot of breakpoints in different files.
In JavaScript, we can also use the debugger keyword. The keyword causes code execution to pause. However, the browser will ignore such a command unless the development tools are open. See the following example.
function writefunction() { console.log("Stop Executing write function!"); debugger; // <-- the debugger stops here } helloWorld();
Backtracking is the process of applying potential solutions to a problem in a JavaScript program. The procedure begins at the location where a specific error is discovered. From there, the complete source code is traced backward. The stages involved in this are:
Keep repeating this until the error is removed and the expected output is obtained.
Using JavaScript’s strict mode makes writing standardized and readable JavaScript programs easier. We can put a program under a strict operating perspective by using strict mode. This strict context forbids specific actions and throws exceptions. It helps reduce bugs and keep the code clean. For example, JavaScript will throw an error in strict mode if we assign values to undeclared variables. The use strict statement enables the strict mode.
VS Code provides easy and straightforward solutions for debugging. Visual Studio Code debuggers support many languages and platforms, which are either built-in or accessed by extensions. Let’s work on VS Code debugging with sample JavaScript code.
const hotels = []; export function addHotel(hotel, stars) { const id = ++hotels.length; let numType = 'odd'; if (id % 2) { numType = 'even'; } hotels.push({ id, hotel, stars, numType, }); }
In this example, you will notice some common bugs. Let’s ignore them for now and add some lines to test the code manually.
addHotel('Kingsburry', '5'); addHotel('Hilton', '5'); addHotel('Cinnamon Grand', '5');
Now, let’s use VS Code’s built-in breakpoints to break the program’s execution wherever we want to test when the bugs occur.
We discussed breakpoints. As you can see in the previous code, the red dots on the left side of VS Code editor are the breakpoints. You can add these by clicking on the panel to the left of the line numbers. Then, on the action bar, click the debug icon.
Take a look at the top section. You will notice a gear icon. Click it. A debug configuration file named launch.json will be prompted. Update the configuration with reference to the following code to enable the VS Code debugger on App.js.
"configurations": [ { "type": "node", "request": "launch", "name": "Launch App", "program": "${workspaceFolder}\\debugapp\\src\\App.js" } ]
Now, click the play icon at the top of the debugger panel. A toolbar will appear at the top of the VS Code. The toolbar will contain several icons you can use to manipulate the debugging process.
In the previous screenshot, you’ll notice that the debugger has paused on your first breakpoint. To continue the session, press the play icon, which will cause execution to continue until it reaches the next breakpoint. Clicking the play icon again will finish the execution and end the debugging session. Let’s understand what the sections on the left pane provide us with:
The watch panel tracks expressions in our code. The expression will be evaluated on whether it satisfies the criteria set here. You can watch a new expression by clicking the + in the panel and entering an expression.
Watching variables alone isn’t always enough. For example, say we wish to pause the debugging only if a specific requirement is met. Add a standard breakpoint to accomplish this. After adding the breakpoint, right-click on it, choose Edit Breakpoint, and add the conditional statement expression for which you need to pause the debugging.
The call stack helps trace exceptions and determine who called what. You can select an item listed in this pane to see who called it.
Another tool in your VS Code toolbox for debugging is using the debug console. Although it may occasionally be excessive, it will frequently save you time when looking for bugs.
The majority of IDEs and almost all recent browsers include debugging tools, which makes debugging much more straightforward. The browsers also allow for step-by-step code tracing to pinpoint the exact cause of the error. Google Chrome, which many developers use, provides us with debugging solutions for JavaScript. In addition, Chrome provides debugger extensions for VS Code and Chrome DevTools. Chrome DevTools comes built-in with the Google Chrome browser.
Chrome’s debugger helps debug client-side JavaScript code, which runs in Google Chrome straight from VS Code. The Chrome debugger is an extension that needs to be installed in VS Code.
The debugger usually connects to Chrome over its Chrome Debugger Protocol, where files loaded in the browser are mapped to the files opened in VS Code. You can set breakpoints directly in the source code and set up variables to watch along with the entire call stack when debugging without leaving the editor.
Due to the inclusion of a JavaScript debugger in Visual Studio Code, this extension is no longer supported (deprecated) there. The JavaScript debugger fixes problems with Node.js, Chrome, Edge, WebView2, VS Code extensions, and other programs. You can remove the Chrome debugger extension without risk and still have access to the required capabilities.
The finest debugging tool is already included with your Chrome browser, whether you’re working with Angular, React, or Vue applications. The Google Chrome browser includes developer tools (also known as DevTools) that allow developers to edit code directly in the browser, add breakpoints to detect issues, and debug their code more quickly.
To open the DevTools Elements panel, press Command + Option + C on a Mac or CTRL + SHIFT + C on any other operating system.
Let’s review some practical strategies for debugging your code more efficiently with DevTools.
Utilizing snippets is an additional effective method for debugging. Using snippets, you may quickly run and reuse scripts in any area of your app.
To add a snippet:
You can also use DevTools to view the call stack. This is helpful when you’re troubleshooting errors and you need to keep track of changes to the call stack due to many asynchronous methods. Expand the Call Stack panel in the right panel to examine all the current functions in the call stack. This is available in the Sources tab of the DevTools.
Suppose you have a bug that does not return the correct value for a variable, and you want to check its value at a specific point in a function:
You can see that this panel contains a lot of helpful information for troubleshooting bugs.
At times, you might need to prevent some scripts from running while debugging. You can black box them in DevTools rather than commenting them out in your code. Click on the script file you want to ignore in the Sources tab’s left panel. To add a script to the ignore list, right-click the code in the middle panel and choose Add script to ignore list.
Since the DevTools won’t execute this script, you can concentrate more on studying the flawed code and identifying the bug.
DevTools in Google Chrome is a terrific resource for debugging, enhancing network speed, viewing your site in various screen sizes and resolutions, and learning where you can improve the code. Even if Google Chrome is not your regular browser, installing it is highly recommended so you can use these features.
In this article, we went through the different techniques of debugging JavaScript code and the tools used in VS Code and Google Chrome.
VS Code’s debugging tools and Chrome’s DevTools offer significant functionality for debugging JavaScript. You’ll become a more effective debugger once you’ve mastered these tools and your days of unending console.log() will be over.
Thanks for reading. I hope this article helped with the critical concepts of debugging JavaScript.
Syncfusion’s Essential JS 2 is the only suite you will need to build an app. It contains over 80 high-performance, lightweight, modular, and responsive UI components in a single package. Download a free trial to evaluate it today.
If you have any questions or comments, you can contact us through our support forums, support portal, or feedback portal. We are always happy to assist you!