Open CheatSheet Back To List Next Tutorial

VS Code Debugger (Video Tutorial)

VS Code Debugger

Intro

[0:00 Video timestamp]

The Visual Studio Code text editor has a built-in Debugger for JavaScript with extensions available for other programming languages. This tutorial demonstrates how to use the Debugger. 
You can use the Debugger with a web server or with Node.js. 

Live Server: Make sure the VS Code Live Server extension is installed. Live Server starts a local web server for use in development. 
Start and stop Live Server by either:
  • Open the HTML file, right click anywhere in the editor, then select Open with Live Servers.
  • Or Click the Go Live link on the Status Bar at the bottom of the window.

Node.js: You can run the debugger with Node.js.
To see of Node.js is installed on your computer, open the Terminal and enter: node --version.
If that command throws an error instead of returning the Node version then you need to install Node.
The Node Intro tutorial includes installation instructions: learnbycheating.com/subjects/nodejs/node-introduction

Example Code: Examples used in this tutorial are available at github.com/LearnByCheating/debugger-demo.

Read it, watch it, do it, review it: The tutorials on this site follow the read it, watch it, do it, review it pattern.

Read it: This is the written version of the tutorial. There is an accompanying video version that demonstrates the steps taken. There are timestamps below the headings that align to the timestamps in the video.
Watch it: After reading a topic, use the timestamp to view the video version to get a visual representation of the steps. 
Do it: After reading and watching a topic, follow the steps in your own code.

Review it: When you are done with the whole tutorial, open the CheatSheet and review the Debugger category. Make sure you understand everything, and can refer back to the CheatSheet when you are working on your own projects in the future. 



Install Debuggers for other programming languages

[0:17 Video timestamp]

  • The default Debugger in VS Code is for JavaScript, but there are Debuggers for other languages as well. You have to install an extension.
  • To do that, click the Run menu > select Install Additional Debuggers > wait for the list extensions to display > find the language you want > click install.


The Debugger Interface

[0:33 Video timestamp]

Let's start by going over the Debugger interface.

  • Run menu: The Run menu at the top has the most commonly used Debugger commands.

  • The Run and Debug icon is on the activity bar (the first column on the left). Clicking it will open the Debug Sidebar.

  • Debug sidebar: The Debug sidebar has panels that list the variable names and values at the breakpoint you are currently at.
  • It also has panels to Watch particular variables, and the call stack.
  •  Clicking "Views and More Actions" drop-down menu, the three dots at the top of the Debug sidebar, allows you to show or hide the various sidebar panels and the Debug console.

  • Breakpoints: Breakpoints are points where you pause the execution of your code.
    • Just click in the editor margin to add or remove a breakpoint. They show up as red dots. 
    • And they are listed in the Debug sidebar, breakpoints panel:


  • Launch Debugger: There is a button at the top of the Debug sidebar to Launch the Debugger. Launching the Debugger will execute the code and pause at the first breakpoint.

  • Debug Toolbar: The debug toolbar appears when you launch the debugger. It has buttons to go to the next breakpoint, the next line, reload the page, or exit the debugger. 


  • Debug Console: The Debug Console displays your console logs and logpoints.

  • Now let's cover each of these topics in detail.

Launch the Debugger

[1:51 Video timestamp] 

Launch the Node.js Debugger:
You can either launch the Node.js Debugger or a Web Debugger. Let's start with Node.js 
  1. Open the JavaScript file you want to debug in the Editor. 
    • If you are following along with the debug-demo project, open the app.js file.
    • Add a breakpoint on line 6, pausing just before the triple function's return statement.
  2. Launch the Debugger by doing one of the following:
    1. Click the Run and Debug icon to open the Debug sidebar > then click the Run and Debug button
    2. Or Click the Run menu > select Start Debugging.
    3. Or press the Fn+F5 keys.
  3. Then select the Node Debugger.

  • It will run the debugger and pause at the first breakpoint.
  • Click the Stop button on the Debug Toolbar to exit the Debugger.


Web App (Chrome) Debugger:
To debug JavaScript attached to an HTML file:
  1. Open the HTML file. In the debug-demo project open the index.html file. It has a script tag sourcing the script.js JavaScript file.
  2. Launch the Debugger by doing one of the following:
    1. Click the Run and Debug icon to open the Debug sidebar > then click the Run and Debug button
    2. Or Click the Run menu > select Start Debugging.
    3. Or press the Fn+F5 keys.
  3. Select the Web App (Chrome) or (Edge) debugger.

  • It will open the HTML file in the browser, launch the debugger, and pause at the first breakpoint.
  • Click the Stop icon in the Debug Toolbar to exit the Chrome Debugger.


Add a configuration file: Launch.json

[2:45 Video timestamp]

Configuration for a Node app
A typical Node.js project with multiple files will have one file that launches the program. You can create a custom launch configuration for our Debugger so it launches the Node Debugger on our app.js file. 

  • Open the app.js file in the editor > open the Debug sidebar > click the create a launch.json file link > Select the Node.js Debugger > this will create a folder named .vscode containing a launch.json file and open it.

.vscode/launch.json
{
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch program",
      "skipFiles": [
        "<node_internals>/**"
      ],
      "program": "${workspaceFolder}/app.js"
    }
  ]
}

A few things to note:
  • It specifies the Debugger type, which is node.
  • The default name to launch a Node.js debugger is "Launch program".
  • The file it launches its app.js.
  • You can edit the launch.json file if you like.

To launch the debugger using this configuration either:
  1. Open the Debug sidebar > Click the Start debugging button. Make sure it is displaying the name of your custom launch config: 
  2. Or on the the status bar (along the bottom) click on the Debugger launch name: 

  • Then the Debugger will run and pause on the first breakpoint. 
  • Click the stop icon to exit the Debugger.

Configuration for a Web app
  • Now let's add a second launch configuration for the web app. 
  • Open the .vscode/launch.json file in one of the following ways:
    • From the Debug sidebar, click the gear icon ⚙ at the top.
    • Or go directly to your project files by clicking the Explorer sidebar, and open .vscode/launch.json.

  • In the launch file, click the "Add Configuration" button and select "Chrome Launch".
  • It will add a new configuration to the file:
.vscode/launch.json
{
  "configurations": [
    {
      "name": "Launch Chrome",
      "request": "launch",
      "type": "chrome",
      "url": "http://localhost:5500",
      "webRoot": "${workspaceFolder}"
    },
    ...
  ]
}

  • Change the URL port number from 8080 to 5500 since that's the port the VS Code Live Server extension uses. Then save it.
  • Now you have two launch configurations. One for the Node app, and one for the web app. 

To run the debugger using this configuration:
  • Start a local server with the Live Server plug-in by either:
    1. Right click anywhere in the index.html editor > select Launch with Live Server.
    2. Or on the status bar click Go Live: 
  • Then start the Debugger in one of the following ways:
    1. Open the Debug side bar > make sure the Start Debugging button is set to Launch Chrome. If not, click the drop-down menu to change it. Then click the button: 
    2. Or on the the status bar (along the bottom) click on the launch config name: 

  • Then the Debugger will run and pause on the first breakpoint. 
  • Click the stop icon to exit the Debugger.

  • Use the Launch Chrome Debugger for the rest of this tutorial.

Breakpoints

[4:45 Video timestamp] 

  • Breakpoints are points where you pause the execution of your code.
  • You can inspect variable values and the call stack as of the breakpoint. This can be used to track down the source of bugs in your code.

  • Debugger keyword: The JavaScript debugger keyword creates a breakpoint. When we launched the Chrome Debugger, the code in the script.js file paused at the debugger keyword on line 4.
  • Since there are no other breakpoints, clicking the continue button on the Debug toolbar will finish the rest of the script and exit the debugger.

  • Add breakpoints: You can add breakpoints by clicking the editor margin on the line number.
  • Breakpoints are indicated with a red dot.

  • Remove breakpoints: Delete a breakpoint by clicking the red dot. 
  • Or in the Breakpoints panel, hover over the breakpoint line number and click Remove Breakpoint X.

  • Temporarily disable breakpoints: Temporarily disable the breakpoint by unchecking the breakpoint in the Breakpoints panel.
  • Or right click the dot in the editor margin and select Disable breakpoint. 

Advanced breakpoints
[6:02 Video timestamp]

  • Inline Breakpoints: Standard breakpoints are at the beginning of the line. You can add an inline breakpoint elsewhere on the line. Put the cursor where you want the breakpoint then either:
    • Right click on the editor margin, on or near the line number > select Add breakpoint.
    • Or click the Run menu > select New Breakpoint > select Inline Breakpoint.

  • Logpoints: Instead of a breakpoint you can add a logpoint that will log a message or variable value to the Debug Console without having to enter console.log.
  • To insert a logpoint: 
    • Place your cursor where you want the logpoint to be. Then either:
      • Right click on the editor margin, on or near the line number > select Add Logpoint.
      • Or click the Run menu > select New Breakpoint > select Logpoint.
    • In the Log Message box, enter the message you want to log.
      • You can include expressions such as variable names. Put expressions in curly braces: { expression goes here }.  
      • Press enter when it's ready. 
    • Logpoints are indicated with a red diamond.
  • To edit the logpoint, right click on it > select Edit logpoint. 

  • Conditional Breakpoints: Conditional breakpoints pause the code only if the condition is met. 
  • To insert a conditional breakpoint:
    • Place your cursor where you want the conditional breakpoint to be. Then either:
      • Right click on the editor margin, on or near the line number > select Add Conditional breakpoint.
      • Or click the Run menu > select New Breakpoint > select Conditional breakpoint.
    • In the condition box that opens, add a condition that resolves to true or false.
      • For example if you have a parameter named num, and you only want to break if num is greater than 1, then use expression: num > 1 
    • Press enter to save it.
    •  Conditional breakpoints are indicated with a red circle with a horizontal line through it.
  • To edit the conditional breakpoint, right click on it > select Edit breakpoint. 

Exception breakpoints
[8:00 Video timestamp]

  • You can enable breakpoints on thrown errors. In the Debug sidebar breakpoints panel, check the Caught Exceptions and/or Uncaught Exceptions checkboxes to enable them.

  • Caught exceptions are errors thrown in a try catch block. 
  • Uncaught exceptions are errors thrown outside a try catch block.
  • If Caught Exceptions is checked then the code will pause on the first caught exception. 

  • To see it in action, check the Caught Exceptions and Uncaught Exceptions boxes.
  • In the Debug sidebar: click the Start Debugging: Launch Chrome button to launch the Debugger.
  • The on the web page, click the Exceptions button. The handler function in the script.js file will throw an error which will trigger an Exception breakpoint.

  • Practice using all the above types of breakpoints and logpoints until you are comfortable with them.

Debug Toolbar

[8:38 Video timestamp]

  • When you launch the debugger, the code stops executing at the first breakpoint, and the Debug toolbar appears at the top of the editor. It has six buttons: 
  • Clicking the continue button will continue to the next breakpoint. If there are no more breakpoints it will execute the rest of the script.
  • The Restart button will execute the script from the top again.
  • The Step Over button will execute the next method as a single command without inspecting or following its component steps.
  • Clicking the Step Into button will enter the next method and follow the execution line-by-line.
  • The Step Out button will take you out of the function, completing the rest of the statements.
  • The stop button will terminate the current program execution and exit the Debugger.

  • Practice using these buttons on the toolbar until you are comfortable with them.

Debug Sidebar

[10:08 Video timestamp]

  • Once your code is paused in a breakpoint, you can view the panels in the Debug sidebar, including the variables panel, the watch panel, the call stack, and the list of breakpoints.
  • You can hide panels you don't want to see by clicking the Add More ellipsis  at the top of the Debug sidebar and unchecking the panel name.

  • You can move the sidebar to the right side by clicking the View menu > select Appearance > select Move Primary Side Bar Right
  • Move it back to the left the same way: View menu > select Appearance > select Move Primary Side Bar Left.

  • We've already looked at the Breakpoints panel.

Variables Panel
  • The Variables panel shows the variable names and values from the breakpoint grouped by scope. 
    • There are four categories of scope: Global, Script, Block, and Local.
      • Global scope: Variables on the Global scope are everything attached to the window object. That includes all the JavaScript built-in objects, the Web APIs provided by the browser, and any variables you may have assigned in your code to the global scope, which in most cases should be none. Variables in the global scope can be accessed anywhere in your code.
      • Script scope: Are variables in your code that are not inside a function or block. They are available to the rest of your code after they are defined. 
        • Variables declared after the breakpoint are listed but the value is undefined because we haven't gotten to the values in our code yet. 
      • Block scope: If your breakpoint is inside a block, like in an if statement or a loop, then variables within that block are block scoped, and can only be accessed inside that block. There are exceptions though. Variables declared with the var keyword can be accessed outside the block. Variables declared with let or const cannot. 
      • Local scope: If your breakpoint is inside a function then the function parameters and any variables declared inside that function are locally scoped. They cannot be accessed outside that function.

  • Putting breakpoints at different locations in your code and clicking the Continue button will change the variables categories and values depending on where the breakpoint is.

Watch Panel
  • The Watch panel allows you to quickly track the value of one or more specific variables as you step through your code in the Debugger.
  • To add a watch variable, click the plus button and enter the variable name. 
  • You can delete a Watch variable by hovering over it and clicking the X.

    Call Stack
    • The Call Stack shows all the functions that are open at the breakpoint. 
    • If you are not familiar with the call stack it is a bit complicated. There is a separate tutorial that explains the Call Stack in the JavaScript tutorial series called the Event Loop.

    • Practice setting breakpoints throughout your code and looking at the different panels and variable names and values in the sidebar until you are comfortable with this feature.

    Debug Console

    [13:34 Video timestamp]

    • The Debug console displays your console logs and logpoints while in Debug mode.
    • There are a few ways to open it: 
      • Open a Terminal panel, then select the Debug Console tab. 
      • Or click the View menu > select Debug Console.
      • Or in the Debug Sidebar click the Views and More Actions drop-down  then select Debug Console.
    • Click the Clear Console button to clear the Debug Console. 
    • X Click the x to close the Debug Console. 

    • Practice using console logs and logpoints in your code and viewing them in the Debug Console until you are comfortable with this feature.

    Chrome Dev Tools - Debugger

    [14:39 Video timestamp]

    • Chrome DevTools has a Debugger for JavaScript in a web page. It works like the VisualStudio Code's Debugger. 
    • The Live Server extension for VS Code lets you launch a development web server to test your web pages on your computer.
    • To launch the web server you can either right click on the HTML page in the editor, then select "Open With Live Server".
      • Or on the status bar, click Go Live.
    • The web page will open to localhost, which has the IP address 127.0.0.1 on port 5500 by default.
    • Using the Chrome browser with Chrome DevTools installed, you can open DevTools by either: 
      • Right clicking on the page and selecting Inspect.
      • Or pressing Fn+F12.
    • Then select the Sources Tab.
    • To the left is a list of your files. 
    • In the middle is your JavaScript code.
    • To the right is the Debug Sidebar that has panels like VS Code for: Watch, Breakpoints, Call Stack, and Scope. The Scope panel is called Variables in VS Code.
    • To add or remove other breakpoints just click the line number.

    • If you reload the page, it will break on the first breakpoint.
    • The Debug Toolbar is at the upper right. Click continue to go to the next breakpoint.
    • To see console logs, go to the Console tab. 

    • You don't really need to get familiar with this DevTools feature if you are using the VS Code Debugger. Just be aware that it is there in DevTools. 

    Open CheatSheet Back To List Next Tutorial