惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tenable Blog
MyScale Blog
MyScale Blog
罗磊的独立博客
Hugging Face - Blog
Hugging Face - Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
爱范儿
爱范儿
博客园 - 司徒正美
D
Darknet – Hacking Tools, Hacker News & Cyber Security
量子位
N
News | PayPal Newsroom
S
Secure Thoughts
酷 壳 – CoolShell
酷 壳 – CoolShell
L
LINUX DO - 热门话题
有赞技术团队
有赞技术团队
V
Visual Studio Blog
T
Tailwind CSS Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Project Zero
Project Zero
B
Blog RSS Feed
J
Java Code Geeks
Google Online Security Blog
Google Online Security Blog
Last Week in AI
Last Week in AI
Cyberwarzone
Cyberwarzone
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
小众软件
小众软件
博客园 - 【当耐特】
Latest news
Latest news
T
Threat Research - Cisco Blogs
aimingoo的专栏
aimingoo的专栏
博客园_首页
博客园 - 三生石上(FineUI控件)
Engineering at Meta
Engineering at Meta
D
Docker
Forbes - Security
Forbes - Security
Help Net Security
Help Net Security
Apple Machine Learning Research
Apple Machine Learning Research
P
Proofpoint News Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
V2EX - 技术
V2EX - 技术
N
Netflix TechBlog - Medium
The Last Watchdog
The Last Watchdog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Threatpost
Cloudbric
Cloudbric
T
The Exploit Database - CXSecurity.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 叶小钗
Webroot Blog
Webroot Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Debugging JavaScript: The Guide I Wish I Had Earlier (2026)
Alex Chen · 2026-06-01 · via DEV Community

Alex Chen

Debugging JavaScript: The Guide I Wish I Had Earlier (2026)

Debugging is a skill. A learnable skill. Here's the systematic approach that saves hours of frustration.

Step 1: Reproduce the Bug

// Before fixing anything, you MUST reproduce it consistently

// ❌ "It sometimes doesn't work"
// ✅ "When I click the submit button after typing a special character,
//     the form shows an error but only on Chrome 120+"

// Create a minimal reproduction:
// 1. What's the EXACT user action that triggers it?
// 2. What's the EXACT expected behavior?
// 3. What's the ACTUAL behavior?
// 4. What's different about this case vs working cases?

// Reproduction checklist:
const repro = {
  browser: 'Chrome 120 / Firefox 121 / Safari 17',
  os: 'macOS 14 / Windows 11 / Ubuntu 22.04',
  device: 'desktop / mobile (iPhone 15)',
  userState: 'logged in as admin / guest user',
  data: 'user with special chars in name / empty state / >1000 items',
  timing: 'first load / after 10 min idle / during API call',
  network: 'fast WiFi / slow 3G / offline mode',
};

// If you can't reproduce it → add logging to capture when it happens

Step 2: Read the Error Message Carefully

// Most developers skip this step. Don't.

// Example error:
// TypeError: Cannot read properties of undefined (reading 'map')
//    at UserProfile.jsx:23:15
//    at renderWithHooks (react-dom.development.js:14985)
//    ...

// Break it down:
// 1. Type of error: TypeError (wrong type being used)
// 2. What happened: Trying to read .map on undefined
// 3. Where: UserProfile.jsx line 23, column 15
// 4. Call stack: How we got there (most recent at top)

// Common error patterns and what they mean:

// TypeError: Cannot read properties of null/undefined
// → Something you expect to exist doesn't
// Fix: Add optional chaining or guard clause
data?.items?.map(item => ...)  // ✅ Safe navigation

// TypeError: X is not a function
// → You're calling something that isn't a function
// Common causes: typo, wrong import, calling on wrong type
getUser()           // ✅ Function
getUser            // ❌ Not calling it (returns function itself)
obj.getUser()      // ❌ obj.getUser might be undefined

// ReferenceError: X is not defined
// → Variable doesn't exist in current scope
// Common causes: typo, out of scope, not imported
const userId;       // Declared but never assigned → undefined
// vs
userId;            // Never declared → ReferenceError!

// SyntaxError: Unexpected token
// → Your code has a syntax error (usually missing bracket/paren)
// Check: matching {}, [], (), '', "", ; placement

// RangeError: Maximum call stack size exceeded
// → Infinite recursion or too deep nesting
function recurse() { return recurse(); } // Stack overflow!

Step 3: Console Methods You Should Use

// console.log is fine, but these are BETTER:

// console.table — Beautiful data display
const users = [
  { id: 1, name: 'Alice', role: 'admin' },
  { id: 2, name: 'Bob', role: 'user' },
  { id: 3, name: 'Carol', role: 'moderator' },
];
console.table(users);
// Shows formatted table with columns!

// console.group — Group related logs
console.group('API Call: /users');
console.log('Request:', { method: 'GET', url: '/users' });
console.log('Response:', userData);
console.log('Duration:', `${Date.now() - start}ms`);
console.groupEnd();

// console.assert — Conditional logging (only shows when WRONG)
console.assert(user.age >= 18, 'User is underage!', user.age);
// Only logs if age < 18

// console.time / timeEnd — Performance measurement
console.time('fetchUsers');
await fetchUsers();
console.timeEnd('fetchUsers'); // Output: fetchUsers: 142ms

// console.count — Count how many times something happens
function handleRequest(req) {
  console.count('requests'); // Counts each call
}
// Output: requests: 1, requests: 2, requests: 3...

// console.trace — Show how you got here (call stack!)
function process(data) {
  console.trace('Processing data');
  // Shows full stack trace leading to this point
}

// console.dir — Inspect object properties deeply
console.log(document.body);   // Shows DOM element briefly
console.dir(document.body);   // Shows ALL properties and methods

// %o / %O / %s / %d / %i — Formatted output
console.log('User %s (ID: %d) is %o', name, id, userObj);

// CSS styling in console
console.log(
  '%c ERROR! ',
  'background: red; color: white; font-weight: bold; padding: 2px 6px;',
  errorMessage
);

Step 4: Chrome DevTools Like a Pro

// === Network Tab ===
// Find failed API calls, check response status, inspect headers
// Filter by: Fetch/XHR for API calls only
// Right-click any request → Copy as curl → share with teammates

// === Sources Tab (Breakpoints) ===
// Click line number → set breakpoint (red dot)
// Execution pauses when that line runs
// Then you can:
// - Hover over variables to see their values
// - Use Console to run expressions in current scope
// - Step Over (F10): Execute next line
// - Step Into (F11): Dive into function call
// - Step Out (Shift+F11): Exit current function

// Conditional breakpoints (game changer!)
// Right-click breakpoint → Edit breakpoint → enter condition:
// user.id === 'problematic-user-id'  // Only pause for this user
// items.length > 1000                // Only pause for large arrays
// response.status >= 400              // Only pause on errors

// Logpoint breakpoints (no pause, just log!)
// Right-click breakpoint → Add logpoint → expression:
// `User ID: ${user.id}, Items: ${items.length}`
// Logs to console without stopping execution!

// DOM breakpoints (catch code modifying DOM):
// Elements tab → right-click element → Break on:
// - Subtree modifications (child added/removed)
// - Attribute modifications (class changed)
// - Node removal (element deleted)

// === Call Stack Panel ===
// When paused, see HOW you got here
// Click any frame → jump to that code location
// Essential for understanding async code flow!

// === Memory Tab (for memory leaks) ===
// Heap snapshot: Compare before/after to find leaked objects
// Allocation sampling: See which functions allocate most memory
// Allocation instrumentation on timeline: Memory over time

// Quick workflow:
// 1. Take heap snapshot before action
// 2. Perform action (navigate, click, etc.)
// 3. Take another snapshot
// 4. Compare: Objects with +count between snapshots = potential leak

Step 5: Source Maps & Production Debugging

// Problem: Production code is minified (unreadable)
// Solution: Source maps link production code back to source

// webpack config:
devtool: 'source-map',        // Full source map (accurate but large file)
// Options: eval-source-map (faster), cheap-source-map (smaller),
//          hidden-source-map (no reference in bundle, for error tracking only)

// Error tracking with source maps:
// Sentry, Rollbar, Bugsnag all auto-apply source maps
// Result: Production errors show original file + line number!

// Manual source map usage:
// If you have an error from production:
// Error: TypeError at main.bundle.js:12345:12
// Use source map to find: src/components/UserForm.tsx line 45

// Generate source maps even for CLI tools:
// # sourceMappingURL=main.js.map
// Upload map to error tracking service (don't expose publicly!)

Step 6: Common Bugs & Their Fixes

// BUG #1: Async state updates (React example, but applies everywhere)
// ❌ State not updated yet
const [data, setData] = useState([]);
fetchData().then(result => {
  console.log(data); // [] — still old value! setData hasn't re-rendered yet
});
// ✅ Use the result directly
fetchData().then(result => {
  setData(result);
  console.log(result); // Fresh data
});

// BUG #2: Closure in loop
for (var i = 0; i < 5; i++) {
  setTimeout(() => console.log(i), 100); // All log 5!
}
// ✅ Fix: let (block scoped) or IIFE
for (let i = 0; i < 5; i++) {  // let creates new binding per iteration
  setTimeout(() => console.log(i), 100); // Logs 0, 1, 2, 3, 4
}

// BUG #3: Object mutation (shared reference)
const original = { items: [1, 2, 3] };
const copy = original;
copy.items.push(4); // Also modifies original!
// ✅ Deep clone
const safeCopy = JSON.parse(JSON.stringify(original));
// Or use structuredClone(obj) (modern, handles more types)

// BUG #4: Floating point math
0.1 + 0.2 !== 0.3  // true! (0.30000000000000004)
// ✅ Use appropriate comparison
Math.abs((0.1 + 0.2) - 0.3) < Number.EPSILON  // true
// Or use decimal libraries for financial calculations

// BUG #5: this context loss
const obj = {
  name: 'Alice',
  greet() {
    console.log(`Hello, ${this.name}`);
  }
};
const fn = obj.greet;
fn(); // Hello, undefined — this is lost!
// ✅ Bind, arrow functions, or .call/.apply
fn.call(obj);         // Hello, Alice
const bound = obj.greet.bind(obj);
bound();              // Hello, Alice

// BUG #6: Race conditions
let currentUser = null;
fetch('/api/user').then(u => { currentUser = u; });
fetch('/api/settings').then(s => {
  console.log(currentUser); // Might be null if settings returns first!
});
// ✅ Chain promises properly
fetch('/api/user')
  .then(u => { currentUser = u; return fetch('/api/settings'); })
  .then(s => { console.log(currentUser); }); // Always defined


What's your favorite debugging technique? What bug took you longest to find?

Follow @armorbreak for more practical developer guides.