Front-end programming is fun, and developers have the ability to create whatever they want, whatever effects they want. Unfortunately, this fun is lost when bugs are encountered. The first thing that might come to mind for a JavaScript developer is the alert, console.log statement. Adding console.log() is a quick way to visualize code state.

However, when developing more complex programs, logging everything to the terminal can be frustrating. Visual Studio code (VS code from here) has built-in features that allow easier debugging and variable monitoring.

Let’s see how we can improve the debugging experience!

Preparation conditions

Software to install:

  • Visual Studiocodev1.50Or higher
  • Node. Js 8.0Or more

In this article, you’ll use a simple Node.js script that performs some basic calculations for debugging. The script is as follows:

@param {number} num1 * @param {nunber} num2 * @return {number} num2 */ const sum = (num1, num1) num2) => { const add = num1 + num2; return add; }; @param {number} num */ print = function(num) {console.log(' after iterating, the total is: ${num} '); }; const iterations = 5; let total = 0; console.log(process.env.NODE_ENV); for (let index = 1; index <= iterations; index++) { console.log(`Round: ${index}`); const random = Math.random(); const result = sum(index, random); total += result; } print(total);Copy the code

Debug the Launcher configuration

To start debugging, you typically start by creating a simple debugging configuration that contains a JSON object. A very simple Node.js application can also be debugged without any configuration because VS Code knows it is working with Node.js Code. First, click the icon with the bug and circle it in the activity bar. The DEBUG pane displays. Be sure to set the environment to Node.js and open the project in Visual Studio code.

At the top of the pane, click the drop-down menu and select Add Configuration. This adds a new configuration and opens a new file called Launch. Stores JSON for all debugging configurations. This file is stored in the.vscode folder created by VS code in the project folder.

As shown below, a debug configuration is created to experiment. This particular configuration is called Debug JS. You can call it whatever you like. Naming is especially useful if you need to create several different debug configurations to test different Settings for your project.

The configuration code is as follows:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "Debug Js",
            "program": "${workspaceFolder}/debug/app.js",
            "env":{
                "NODE_ENV":"development"
            }}
        }
    ]
}
Copy the code

The Program property defines the path to the file that needs to be launched for debugging. When the debugger is started, the ${workspaceFolder} variable is replaced with the workspace path. Set the path to the app.js file in a folder called /debug.

Finally, set an environment variable to configure the Node.js application. The env part of the JSON debugging configuration sets environment variables, such as NODE_ENV. This can be used to change behavior, such as log verbosity. Finally, don’t forget to save the launch.json configuration.

Other useful configuration items include:

  • cwd: Launches the program to be debugged in this directory.
  • args: An array of optional arguments passed to the runtime executable. For example, if you want to pass directory paths:"Args" : [" -- dir ", ". / libs "].
  • envFile: Optional path to the file containing the environment variable definition.

Now that you have defined the debug configuration, select the name you created and click the Play arrow to start debugging. The application starts, executes, and ends in debug mode. And display the output.

Add a breakpoint

Normal breakpoints

Set a breakpoint by clicking the margin to the left of the line number. A red dot is added to indicate that the debugger will stop execution of the program at this particular line number. Now add a breakpoint at line 30 to check the value of the total variable.

The sample code loops through a number five times. This number is added to the total variable and printed at the end of the program. Now let’s examine the code by launching the debugger to see if it behaves as expected.

Click the Play icon in the Debug toolbar at the top of the screen to continue executing the code until a new breakpoint is encountered. The total value changes after each round.

Logpoint

Logpoint displays a message like console.log(), which does not stop execution. The message can contain text or delimiters in curly braces {… }. In this case, the reference to {num} is replaced by the current value of the num variable.

To add a new logpoint, right-click the breakpoint and select add logpoint… .

Then enter some appropriate text.

conditionalThe breakpoint

Expression breakpoints allow logging only when certain conditions are met. Assume that logging occurs only when num is greater than or equal to 17. Otherwise, the code won’t crash.

To add an expression breakpoint, right-click the breakpoint and select Conditional, then enter an associated expression.

The breakpoint is executed only when num is greater than or equal to 17.

Hit CountCalculate the breakpoint

To add conditional breakpoints, select Hit Count to add a Hit Count breakpoint. This type of breakpoint is used only to start logging after a particular function or block of code has been hit a certain number of times. Take a loop, which pauses code only when a particular line of code is hit three times.

Run the debug configuration, and when the line of code is clicked a third time, it pauses.

conclusion

It’s clear that Visual Studio Code does a good job of helping developers debug applications. There are many possibilities for setting breakpoints, such as hit counts or expression breakpoints. This is definitely a big improvement over using the console.log() statement, so it also improves development efficiency and allows better reproduction of errors that occur. In general, you can use expressions, observers, or log points with the debugger to provide a better experience.

With debug configuration, you can easily switch between different Settings for your project.