Use console.log() for quick checks, preferably with labels or console.table() for objects; 2. Utilize browser DevTools to set breakpoints, step through code, and inspect variables; 3. Implement try...catch for synchronous and async/await errors, and monitor the Console tab; 4. Apply ESLint and Prettier to catch errors and maintain code consistency; 5. Insert debugger; statements to pause execution where needed; 6. Investigate network requests and DOM issues using the Network and Elements tabs—combining these methods ensures effective JavaScript debugging.
Debugging JavaScript code is a skill every developer uses daily. Here’s how you can effectively find and fix issues in your JavaScript:

1. Use console.log()
for Quick Checks
The simplest and most common way to debug is using console.log()
. Insert it at key points in your code to check variable values, execution flow, or whether a function is being called.
console.log("User data:", userData); console.log("Is active?", isActive);
It's fast and works almost everywhere—browser, Node.js, etc. But don’t leave console.log()
statements in production code.

Pro tip: Use labeled logs to avoid confusion:
console.log("At step 3:", step3Value);
And use console.table()
for arrays or objects—it formats data nicely in tables.

2. Use Browser Developer Tools
Modern browsers (Chrome, Firefox, Edge) have powerful built-in DevTools. Here’s how to use them effectively:
- Open DevTools with
F12
orCtrl Shift I
(Cmd Option I
on Mac). - Go to the Sources (or Debugger) tab.
- Find your JavaScript file and set breakpoints by clicking on line numbers.
- When the code runs, it pauses at the breakpoint.
- Use the controls to step through code:
- Step over
- Step into
- Continue execution
- Inspect variables and the call stack in real time.
You can also:
- Add conditional breakpoints (only trigger when a condition is met).
- Use
debugger;
in your code to force a pause:if (error) { debugger; // Execution stops here if DevTools is open }
3. Handle Errors Gracefully
Use try...catch
blocks for synchronous code to catch runtime errors:
try { riskyOperation(); } catch (error) { console.error("Something went wrong:", error.message); }
For asynchronous code (Promises), use .catch()
or try...catch
with async/await
:
async function fetchData() { try { const res = await fetch('/api/data'); const data = await res.json(); } catch (error) { console.error("Fetch failed:", error); } }
Also check the Console tab in DevTools—JavaScript errors and warnings appear there in real time.
4. Lint and Format Your Code
Use tools like ESLint to catch common mistakes early (e.g., undefined variables, syntax issues):
npx eslint your-file.js
And use Prettier to keep code formatting consistent—sometimes bugs hide in poorly structured code.
5. Use debugger;
Strategically
Insert debugger;
where you want execution to pause (if DevTools is open):
function processUser(user) { debugger; return user.name.toUpperCase(); }
It's like a breakpoint you can toggle quickly.
6. Check Network and DOM Issues
Sometimes the bug isn’t in JavaScript logic but in:
- Failed API calls (check Network tab).
- Elements not found (
document.getElementById
returnsnull
). - Event listeners not attached properly.
Use the Elements tab to inspect if the DOM matches expectations.
Basically, debugging is about observing what your code actually does vs. what you expect it to do. Combine console.log
, DevTools, and structured error handling—and you’ll catch most bugs quickly.
The above is the detailed content of How do you debug JavaScript code?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

C++ multi-thread debugging can use GDB: 1. Enable debugging information compilation; 2. Set breakpoints; 3. Use infothreads to view threads; 4. Use thread to switch threads; 5. Use next, stepi, and locals to debug. Actual case debugging deadlock: 1. Use threadapplyallbt to print the stack; 2. Check the thread status; 3. Single-step the main thread; 4. Use condition variables to coordinate access to solve the deadlock.

How to use LeakSanitizer to debug C++ memory leaks? Install LeakSanitizer. Enable LeakSanitizer via compile flag. Run the application and analyze the LeakSanitizer report. Identify memory allocation types and allocation locations. Fix memory leaks and ensure all dynamically allocated memory is released.

Concurrency testing and debugging Concurrency testing and debugging in Java concurrent programming are crucial and the following techniques are available: Concurrency testing: Unit testing: Isolate and test a single concurrent task. Integration testing: testing the interaction between multiple concurrent tasks. Load testing: Evaluate an application's performance and scalability under heavy load. Concurrency Debugging: Breakpoints: Pause thread execution and inspect variables or execute code. Logging: Record thread events and status. Stack trace: Identify the source of the exception. Visualization tools: Monitor thread activity and resource usage.

This article introduces shortcuts for Go function debugging and analysis, including: built-in debugger dlv, which is used to pause execution, check variables, and set breakpoints. Logging, use the log package to record messages and view them during debugging. The performance analysis tool pprof generates call graphs and analyzes performance, and uses gotoolpprof to analyze data. Practical case: Analyze memory leaks through pprof and generate a call graph to display the functions that cause leaks.

Tools for debugging PHP asynchronous code include: Psalm: a static analysis tool that can find potential errors. ParallelLint: A tool that inspects asynchronous code and provides recommendations. Xdebug: An extension for debugging PHP applications by enabling a session and stepping through the code. Other tips include using logging, assertions, running code locally, and writing unit tests.

The following techniques are available for debugging recursive functions: Check the stack traceSet debug pointsCheck if the base case is implemented correctlyCount the number of recursive callsVisualize the recursive stack

Common PHP debugging errors include: Syntax errors: Check the code syntax to make sure there are no errors. Undefined variable: Before using a variable, make sure it is initialized and assigned a value. Missing semicolons: Add semicolons to all code blocks. Function is undefined: Check that the function name is spelled correctly and make sure the correct file or PHP extension is loaded.

C++ debugging functions that contain exception handling uses exception point breakpoints to identify exception locations. Use the catch command in gdb to print exception information and stack traces. Use the exception logger to capture and analyze exceptions, including messages, stack traces, and variable values.
