Debugging in JavaScript (original) (raw)

Last Updated : 04 Feb, 2025

Debugging is the process of testing, finding, and reducing bugs (errors) in computer programs. It involves:

Types of Errors in JavaScript

**Syntax Errors: Issues with incorrect syntax, preventing execution.

console.log("Hello); // SyntaxError: missing closing quote

**Runtime Errors: Errors occurring during execution.

let a = undefined; console.log(a.length); // TypeError: Cannot read properties of undefined

**Logical Errors: Code runs without errors but produces incorrect results.

function add(a, b) { return a - b; // Logical error: should use + instead of - }

JavaScript Debuggers

1. Built-in Debugging Tools

Modern browsers provide built-in JavaScript debuggers, accessible via Developer Tools. Debuggers can be turned on and off, forcing errors to be reported. They allow setting breakpoints and examining variables while code executes.

**Steps to Activate Debugging:

2. Using console.log()

One of the simplest debugging techniques is logging messages to the console.

let x = 10; console.log("Value of x:", x);

3. Setting Breakpoints

Breakpoints stop execution at specific lines, allowing variable inspection.

4. Using the debugger Keyword

The debugger statement stops execution and opens debugging tools.

function test() { let n = 42; debugger; // Execution pauses here console.log(n); } test();

If debugging is unavailable, debugger has no effect.

Common Debugging Issues and Fixes

1. Debugging Syntax Errors

Syntax errors occur when code violates JavaScript’s syntax rules. These errors are typically caught during compilation.

console.log("Hello);

`

**Fix: Add the missing closing quote.

2. Using console.log() to Track Values

Logging variable values helps debug unexpected outputs.

let x = 5; console.log("X value:", x);

`

3. Debugging with Breakpoints in DevTools

Breakpoints allow developers to pause code execution and inspect variable values.

JavaScript `

function add(a, b) { return a + b; } let res = add(5, 10); console.log(res);

`

**Output

4. Identifying undefined Variables

Undefined variables usually indicate scope issues or missing arguments.

function greet(name) { console.log("Hello, " + name); } greet(); // Undefined issue

`

**Fix: Call greet(“Ajay”) to pass a valid argument.

5. Catching Errors with try…catch

try { let data = JSON.parse("{invalid}"); } catch (error) { console.error("Parsing error:", error.message); }

**Fix: Ensure valid JSON input.

6. Debugging Asynchronous Code with Promises

fetch("invalid-url").catch(error => console.error("Request failed", error));

**Fix: Handle network errors gracefully.

7. Debugging Event Listeners

document.getElementById("btn").addEventListener("click", function() { console.log("Button clicked"); });

**Fix: Ensure the element ID exists.

8. Memory Leak Detection

let a = [];
setInterval(() => a.push("data"), 1000); // Potential memory leak

**Fix: Clear unused data regularly.