DEV Community

Cover image for Debugging in JS
_Khojiakbar_
_Khojiakbar_

Posted on

Debugging in JS

Debugging in JavaScript is like being a detective in your code. Imagine your code is a mystery novel, and sometimes the plot gets tangled. The debugger is your magnifying glass, helping you zoom in on the tricky parts and figure out what's going wrong.

Image description

Why Do We Need a Debugger?

  1. Find Bugs: Bugs are like tiny gremlins messing with your code. The debugger helps you catch them in action.

  2. Understand Flow: It lets you see how your code runs step-by-step, which can be super enlightening.

  3. Inspect Variables: You can check the value of variables at different points in your code.

How Do We Use It?

Basic Example: Catching the Cookie Thief

Imagine you're running a bakery and have a code snippet to keep track of your cookies. But for some reason, cookies keep disappearing!

function bakeCookies() {
  let cookies = 10;
  console.log("Cookies before thief: " + cookies);
  // Mysterious cookie thief!
  cookies -= 3;
  console.log("Cookies after thief: " + cookies);
}

bakeCookies();
Enter fullscreen mode Exit fullscreen mode

To catch the cookie thief, you can use the debugger.

  1. Add the debugger Keyword:
    When you run this in your browser's developer tools (usually by pressing F12), the code will pause at the debugger line. Now, you can inspect variables and step through the code.

  2. Using Developer Tools:

  • Open Developer Tools (usually F12 or right-click on the page and select "Inspect").
  • Go to the "Sources" tab.
  • You'll see the code paused at the debugger line.
  • Use "Step over" (F10) to go to the next line.
  • Use "Step into" (F11) to dive into functions.
  • Check the "Scope" section to see the values of your variables.

Another Fun Example: The Uncooperative Robot

Imagine you have a robot that should count to 5, but it's not cooperating.

function robotCount() {
  for (let i = 1; i <= 5; i++) {
    debugger; // Pause and check what i is
    console.log("Robot says: " + i);
  }
}

robotCount();
Enter fullscreen mode Exit fullscreen mode

When you run this, the debugger will pause on each iteration of the loop. You can watch i increment and see if it ever misbehaves.

Tips for Using the Debugger

  1. Breakpoints: You can set breakpoints by clicking on the line numbers in the "Sources" tab. This is a great way to pause execution without modifying your code with debugger.
  2. Watch Expressions: You can add variables to the "Watch" panel to keep an eye on their values.
  3. Call Stack: Check the "Call Stack" panel to see how your code reached the current point.

Why It's Fun

Using the debugger is like being Sherlock Holmes in your own code. You get to investigate, uncover mysteries, and catch bugs red-handed. Plus, it's incredibly satisfying to see your code work perfectly once you've sorted out the issues.

Top comments (0)