How do you see JavaScript code in Chrome and use the debugger for debugging?

I want to debug some JavaScript code in Google Chrome. What’s the best way to open the debugger and inspect or step through the code?

Using Chrome DevTools (Classic and Powerful)

  1. Open DevTools: Press F12 or Ctrl + Shift + I (Windows/Linux) or Cmd + Option + I (Mac) to open Chrome DevTools. Alternatively, right-click on the page and select Inspect.

  2. Go to the Sources Tab: This tab allows you to view and step through your JavaScript code.

  3. Set Breakpoints: In the “Sources” tab, navigate to the file you’re working with, and click on the line number where you want to set a breakpoint. The code execution will pause when it reaches this line, allowing you to inspect variables, step through the code, and debug.

  4. Use the Console: You can also use the “Console” tab to interact with the page and run JavaScript expressions directly.

Chrome DevTools is a powerful built-in tool that allows you to view and debug JavaScript code with ease. It’s widely used by developers for all kinds of web debugging tasks.

Using debugger Statement (Manual Control) :

function testFunction() {
  debugger; // Execution will pause here
  console.log("This is a test");
}
  1. Insert the debugger statement in your JavaScript code where you want execution to pause.

  2. Open Chrome DevTools and run your code. The debugger will pause at the debugger statement, allowing you to inspect variables and step through the code.

The debugger statement is a quick way to stop code execution and start debugging without manually setting breakpoints in DevTools.

Using Console Log Statements (Simple Debugging) :


console.log("Value of x:", x);
  1. If you prefer a simpler approach, you can use console.log() to output values directly to the “Console” tab in Chrome DevTools.

  2. Use console.log() in different parts of your code to track variable values and flow, which can help you identify issues.

console.log() is great for quick checks and simpler debugging tasks. It’s often used in combination with DevTools for a lightweight debugging experience.