JavaScript Debugging

Programming code might contain syntax errors, or logical errors. Many of these errors are difficult to diagnose. To make things even worse, often, when programming code, especially JavaScript code, contains errors nothing will happen. There are no error messages, and you will get no indications where to search for errors.

Searching for (and fixing) errors in programming code is called code debugging and this document aims to help you in the debugging process of your JavaScript code.

Different Debugging Methods

Knowing your tools can make a significant difference when it comes to getting things done. Despite JavaScript’s reputation as being difficult to debug, if you keep a couple of tricks up your sleeve errors and bugs will take less time to resolve.

console.log() and friends

The easiest and most used method of debugging JavaScript code is to log out messages and variables to the browser console. console.log() is most often used for this purpose but the console object has many other useful methods too.

Read more:

  1. https://developer.mozilla.org/en-US/docs/Web/API/console

  2. https://blog.webdevsimplified.com/2022-03/console-methods/

Or if you prefer a video:

Browser Debugger and debugger statement

All modern browsers have a built-in JavaScript debugger. Built-in debuggers can be turned on and off, forcing errors to be reported to the user.

With a debugger, you can also set breakpoints (places where code execution can be stopped), and examine variables while the code is executing.

Usually, you activate debugging in your browser with the F12 key, and select “Console” in the debugger menu.

The debugger keyword inside your code stops the execution of JavaScript, and calls (if available) the debugging function. This has the same function as setting a breakpoint in the debugger. If no debugging is available, the debugger statement has no effect.

Read more:

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger

  2. https://firefox-source-docs.mozilla.org/devtools-user/debugger/index.html

Or if you prefer video:

NOTE: The method to debug inside VSCode shown in the video below is outdated! You don’t need to install a debugger extension to VSCode but you still need the LiveServer extension installed

Debugging inside VSCode

Probably the most flexible way of debugging your JavaScript is to do it inside VSCode. The following video shows how to do it:

NOTE: You need to have LiveServer extension installed in your VSCode for this to work!