0
0
JavascriptDebug / FixBeginner · 4 min read

How to Debug JavaScript in Chrome: Step-by-Step Guide

To debug JavaScript in Chrome, open Chrome DevTools with F12 or Ctrl+Shift+I, then use the Sources tab to set breakpoints in your code. You can step through code line-by-line, inspect variables, and use the Console to test expressions and view errors.
🔍

Why This Happens

JavaScript errors or unexpected behavior happen because the code runs in the browser without stopping, making it hard to see what goes wrong. Without debugging, you only see error messages or broken output but not the exact cause.

javascript
function greet(name) {
  console.log('Hello ' + name);
}

greet(); // Called without argument, causes undefined output
Output
Hello undefined
🔧

The Fix

Open Chrome DevTools by pressing F12 or Ctrl+Shift+I. Go to the Sources tab and find your JavaScript file. Click on the line number to set a breakpoint where you want the code to pause. Reload the page or trigger the code to stop at the breakpoint. Use the step buttons to move through the code and watch variable values.

You can also use the Console tab to check for errors and run JavaScript commands directly.

javascript
function greet(name) {
  debugger; // This line pauses execution when DevTools is open
  console.log('Hello ' + name);
}

greet('Alice');
Output
Hello Alice
🛡️

Prevention

To avoid debugging headaches, write clear code and use console.log() to check values during development. Use Chrome DevTools regularly to set breakpoints and inspect variables. Enable linting tools like ESLint to catch common mistakes before running code. Keep your code modular and test small parts often.

⚠️

Related Errors

Common related errors include ReferenceError when variables are not defined, TypeError when calling methods on wrong types, and SyntaxError from typos. Using Chrome DevTools breakpoints and the console helps quickly identify and fix these.

Key Takeaways

Use Chrome DevTools Sources tab to set breakpoints and step through code.
Open DevTools with F12 or Ctrl+Shift+I to start debugging.
Use console.log() and the Console tab to inspect values and errors.
Enable linting tools like ESLint to catch errors early.
Write modular code and test small parts to simplify debugging.