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!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 assignmentBug: 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.