Table of Contents
7. Check Console for Errors and Logs
Bonus Tips
Home Web Front-end JS Tutorial How to debug JavaScript in Chrome?

How to debug JavaScript in Chrome?

Jul 30, 2025 am 04:56 AM

Open Chrome DevTools by right-clicking on the page, select "Inspect" or use the shortcut keys F12, Ctrl Shift I (Windows/Linux) or Cmd Option I (Mac), and switch to the "Sources" tab for JavaScript debugging. 2. Find and open the target .js file in the file tree on the left side of the Sources panel. If you use the framework, you need to locate it in directories such as top, localhost, or webpack://. 3. Set the line breakpoint by clicking the line number, add the conditional breakpoint by right-clicking the line number, or set the event listening breakpoint in the "Event Listener Breakpoints" on the right, and click the "Pause on exceptions" button to enable exception breakpoints. 4. After the code is paused, use the top control button to continue executing (▶️), skip the function line by line (⏯️), enter the function (⤵️), jump out the function (⤴️), or pause the next call (||). 5. When pausing, view the variable value in the Scope panel on the right, hover the code variable to view its current value, use Console to execute expressions, or add expressions to monitor such as items.length in the Watch area. 6. Insert a debugger into the code; the statement can automatically pause during runtime, which is convenient for debugging dynamic or compressed code, but you need to pay attention to removing the statement in the production environment to avoid unexpected interrupts. 7. The Console panel displays outputs such as console.log(), console.error(), as well as syntax errors, runtime exceptions and network problems. You can use console.table() to display the object array in a tabular form. 8. If the problem occurs in the page loading stage, you can set a breakpoint in advance, insert a debugger; statement, or reload the page through Ctrl R (Cmd R) when DevTools is turned on to trigger a breakpoint immediately. In addition, you can click the {} button to beautify the compressed code, right-click the script and select "Blackbox script" to ignore third-party libraries, and use Ctrl Shift F to search for file content globally, thereby improving debugging efficiency. By proficiently using breakpoints, single-step execution and real-time variable inspection, Chrome DevTools can effectively improve the efficiency of JavaScript debugging. The key is to practice in combination with actual code and master the call stack and scope analysis.

How to debug JavaScript in Chrome?

Debugging JavaScript in Chrome is straightforward once you know the tools and techniques. The Chrome DevTools provides a powerful, built-in environment for stepping through code, inspecting variables, and identifying issues. Here's how to do it effectively:

How to debug JavaScript in Chrome?

1. Open Chrome DevTools

To start debugging, open the Developer Tools:

  • Right-click on the page and select "Inspect" , or
  • Press F12 or Ctrl Shift I (Windows/Linux), Cmd Option I (Mac).

Make sure you're on the "Sources" tab (or "Debugger" in older versions), where you can view and debug your JavaScript files.

How to debug JavaScript in Chrome?

2. Find Your JavaScript File

In the Sources panel:

  • Navigate through the file tree in the left sidebar to locate your .js file.
  • If you're using a framework or bundler (like React, Vue, or Webpack), look under folders like top , localhost , or webpack:// .

Once you find the file, click to open it in the editor.

How to debug JavaScript in Chrome?

3. Set Breakpoints

Breakpoints pause code execution so you can inspect the current state.

Ways to set breakpoints:

  • Line-of-code breakpoint : Click the line number in the source code. The code will pause before that line runs.
  • Conditional breakpoint : Right-click a line number → "Add conditional breakpoint" . Useful for pausing only when certain conditions are met (eg, i === 5 ).
  • Event listener breakpoints : Under the "Event Listener Breakpoints" section (right sidebar), you can pause when events like clicks, keypresses, or form submissions occur.
  • Exception breakpoint : Click the “Pause on exceptions” button (⏹️) in the top bar to stop when an error is thrown.

4. Step Through Code

Once paused at a breakpoint, use the controls to navigate:

  • ▶️ Resume/Continue : Run until the next breakpoint.
  • ⏯️ Step over : Execute the next line (without entering functions).
  • ⤵️ Step into : Enter a function call to debug inside it.
  • ⤴️ Step out : Finish the current function and return to the caller.
  • || Pause on next call : Temporarily pause execution.

These controls appear at the top of the DevTools when paused.


5. Inspect Variables and Scope

While paused:

  • Check the Scope panel (right sidebar) to see current values of variables (local, closure, global).
  • Hover over variables in the code to see their current values.
  • Use the Console tab to log or evaluate expressions in the current context (eg, type user.name to check a property).

You can also watch specific expressions:

  • In the "Watch" section, click and enter a variable or expression (eg, items.length ).

6. Use debugger; Statement

Insert debugger; directly in your JavaScript code:

 function saveUser(user) {
  if (!user.id) {
    debugger; // Execution will pause here when DevTools is open
  }
  // ...
}

This is helpful when you can't easily set a breakpoint in the DevTools (eg, minified code or dynamic scripts).

⚠️ Remove debugger; statements in production — they'll halt execution if DevTools is open.


7. Check Console for Errors and Logs

The Console tab shows:

  • console.log() , console.error() , console.warn() output
  • Syntax errors, runtime exceptions, and network issues
  • Warnings about deprecations or mixed content

Use console.log() strategically to trace values:

 console.log('User object:', user);

You can also use console.table() for arrays of objects — it displays them in a neighbor table.


8. Reload and Debug on Page Load

If your issue happens during page load:

  • Set a breakpoint before the code runs, or
  • Use debugger; in the early code, or
  • Press Ctrl R (or Cmd R ) while DevTools is open to reload and hit breakpoints immediately.

Bonus Tips

  • Pretty-print minified code : Click the {} (Pretty Print) button at the bottom of the Sources panel to format minified JS for readingability.
  • Blackbox third-party scripts : Right-click a script in Sources → "Blackbox script" to skip over libraries like jQuery or React during debugging.
  • Search across files : Press Ctrl Shift F to search all JS files for a function or variable name.

That's it. With breakpoints, step-through execution, and real-time inspection, Chrome's DevTools make JavaScript debugging efficient. The key is practicing with real code and learning to read the call stack and scope data. Basically, just open DevTools, set a breakpoint, and go.

The above is the detailed content of How to debug JavaScript in Chrome?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

RimWorld Odyssey How to Fish
1 months ago By Jack chen
Can I have two Alipay accounts?
1 months ago By 下次还敢
Beginner's Guide to RimWorld: Odyssey
1 months ago By Jack chen
PHP Variable Scope Explained
3 weeks ago By 百草

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1506
276
How to make an HTTP request in Node.js? How to make an HTTP request in Node.js? Jul 13, 2025 am 02:18 AM

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

How to Check if an Array Includes a Value in JavaScript How to Check if an Array Includes a Value in JavaScript Jul 13, 2025 am 02:16 AM

In JavaScript, check whether an array contains a certain value. The most common method is include(), which returns a boolean value and the syntax is array.includes(valueToFind), for example fruits.includes('banana') returns true; if it needs to be compatible with the old environment, use indexOf(), such as numbers.indexOf(20)!==-1 returns true; for objects or complex data, some() method should be used for in-depth comparison, such as users.some(user=>user.id===1) returns true.

Advanced JavaScript Scopes and Contexts Advanced JavaScript Scopes and Contexts Jul 24, 2025 am 12:42 AM

The scope of JavaScript determines the accessibility scope of variables, which are divided into global, function and block-level scope; the context determines the direction of this and depends on the function call method. 1. Scopes include global scope (accessible anywhere), function scope (only valid within the function), and block-level scope (let and const are valid within {}). 2. The execution context contains the variable object, scope chain and the values of this. This points to global or undefined in the ordinary function, the method call points to the call object, the constructor points to the new object, and can also be explicitly specified by call/apply/bind. 3. Closure refers to functions accessing and remembering external scope variables. They are often used for encapsulation and cache, but may cause

How to Get the Value of an Input Field in JavaScript How to Get the Value of an Input Field in JavaScript Jul 15, 2025 am 03:09 AM

To get the value of the HTML input box, the core is to find the corresponding element through the DOM operation and read the value attribute. 1. Use document.getElementById to be the most direct way. After adding an id to input, you can get the element and read the value through this method; 2. Use querySelector to be more flexible, and you can select elements based on attributes such as name, class, type, etc.; 3. You can add input or change event listeners to achieve interactive functions, such as obtaining input content in real time; 4. Pay attention to the script execution timing, spelling errors and null judgment, and ensure that the element exists before accessing the value.

How to get the value of a selected radio button with JS? How to get the value of a selected radio button with JS? Jul 18, 2025 am 04:17 AM

There are two core methods to get the selected radio button value. 1. Use querySelector to directly obtain the selected item, and use the input[name="your-radio-name"]:checked selector to obtain the selected element and read its value attribute. It is suitable for modern browsers and has concise code; 2. Use document.getElementsByName to traverse and find the first checked radio through loop NodeList and get its value, which is suitable for scenarios that are compatible with old browsers or require manual control of the process; in addition, you need to pay attention to the spelling of the name attribute, handling unselected situations, and dynamic loading of content

JavaScript Template Literals: Syntax and Use Cases JavaScript Template Literals: Syntax and Use Cases Jul 13, 2025 am 02:28 AM

Template strings are a feature introduced in JavaScriptES6, which wraps content with backticks and supports variable interpolation and multi-line strings. 1. Use backticks to define strings such as Thisisatemplateliteral; 2. Insert variables or expressions through ${} syntax such as Iam${age}yearsold.; 3. Naturally support multi-line text without manually adding newlines. Common scenarios include dynamically generating HTML content, multi-line string output, and simplified conditional logical stitching. Notes include avoiding injection attacks, advanced usage of tag templates, and keeping logic simple.

Building Secure Sandboxed Iframes with JavaScript Building Secure Sandboxed Iframes with JavaScript Jul 16, 2025 am 02:33 AM

To use JavaScript to create a secure sandbox iframe, first use the sandbox attribute of HTML to limit iframe behavior, such as prohibiting script execution, pop-up windows and form submission; secondly, by adding specific tokens such as allow-scripts to relax permissions as needed; then combine postMessage() to achieve secure cross-domain communication, while strictly verifying message sources and data; finally avoid common configuration errors, such as not verifying the source, not setting up CSP, etc., and perform security testing before going online.

See all articles