🟒 EasyWhat's Wrong?πŸ› Debug Challenge

Accidental global variable

Buggy Code β€” Can you spot the issue?

function calculateTotal(items) {
  total = 0; // forgot let/const/var!
  items.forEach(item => {
    total += item.price;
  });
  return total;
}

calculateTotal([{ price: 10 }, { price: 20 }]);
console.log(window.total); // 30 β€” leaked to global!

Fixed Code

function calculateTotal(items) {
  let total = 0; // properly declared
  items.forEach(item => {
    total += item.price;
  });
  return total;
}

// Better: use reduce
function calculateTotal(items) {
  return items.reduce((sum, item) => sum + item.price, 0);
}

// Enable strict mode to catch this at runtime:
// 'use strict'; β€” throws ReferenceError on undeclared assignment

Bug Explained

Bug: Assigning to total without declaring it creates an implicit global variable (window.total in browsers). This can cause bugs if called multiple times or in parallel.

Explanation: Always declare variables. "use strict" makes implicit globals throw a ReferenceError, catching this at runtime. ESLint catches it statically.

Key Insight: Forgot let/const/var = implicit global. "use strict" turns this into a ReferenceError. Always use a linter.

More What's Wrong? Debug Challenges

🟑 MediumWrong comparison with NaNβ†’πŸ”΄ HardInfinite re-render in React useEffectβ†’πŸŸ‘ MediumArray sort mutates originalβ†’πŸŸ‘ MediumSpread only shallow-copies nested arraysβ†’

Practice spotting bugs live β†’

38 debug challenges with AI hints

πŸ› Try Debug Lab