Debugging in JavaScript

Debugging in JavaScript

Having bugs that affect the output of our code can be frustrating, so knowing how to debug is a skill that developers should have.

When I first started learning to code, I would frequently hear the term "debugging" and wonder what it meant. This article will define debugging and show you how to debug your JavaScript code.

First, let us discuss bugs.

Bugs are simply errors or flaws. An error in the code causes the program to malfunction or produce unsatisfactory results.

Bugs aren't always bad; they help us identify problems in our code.

The act of finding bugs in code is known as Debugging. It entails running the code step by step to determine the exact location of the problem.

Debugging in JavaScript can be carried out in different ways. They include:

  1. Using the Console.log() method
  2. Using Debugger
  3. Setting Breakpoint

Console.log() method: The console.log method is a quick and easy way to debug. JavaScript values or inputs can be shown in the debugger window by using console.log().

<script>
let a = 4;
let b = 3;
c = a + b;
console.log(c);
</script>

Using Debugger: Using the debugger keyword is another method for debugging. The Debugger keyword forces the JavaScript execution to halt and invokes the debugging function.

<script>
let a = 4;
let b = 3;
c = a + b;

//stops the execution
debugger;

console.log(c);

</script>

Screenshot (759).png

Setting Breakpoint: JavaScript breakpoints can be set in the debugger window. Setting breakpoints allows you to examine your JavaScript values by stopping execution at each breakpoint.

How to set Breakpoints

  1. Open your debugger window. (Press F12)
  2. Go to the Sources tab.
  3. Open the file containing the desired codes.
  4. Navigate to the line of code.
  5. Locate the number column to the left of your line of code and click on it (It shows a blue mark). A breakpoint has been set.

Screenshot (758).png