Debugging JavaScript Errors


Common JavaScript Errors

Examples include undefined is not a function, Uncaught ReferenceError, or syntax mistakes.

How to Fix:

1. Use Console Logs

Add console.log() to track variable values:


function calculateTotal(price, tax) {
  console.log("Price:", price, "Tax:", tax); // Debugging line
  return price * (1 + tax);
}
    

2. Check Syntax

Example of a syntax error (missing ;):


let name = "Alice"
alert(name) // Missing semicolon
    

Fixed code:


let name = "Alice";
alert(name);
    

3. Use Debugger Statement

Pause execution with debugger:


function init() {
  debugger; // Execution pauses here
  // ...code
}
    

4. Validate JSON

Use JSONLint to fix malformed JSON:


// Invalid JSON
{ "name": "Alice", "age": 30, }

// Valid JSON
{ "name": "Alice", "age": 30 }
    

Prevention Tips

  • Use ESLint to catch errors early.
  • Test code in a sandbox (e.g., CodePen).
Note: Always check the browser console (F12 → Console) for real-time error tracking.

Did you find this article useful?