30 JavaScript Mistakes Almost Every Developer Makes (and How They Quietly Break Production)
By Sujan Miah
If you write JavaScript long enough, you will ship a bug that makes you stare at the screen and say, “But it worked on my machine.” I have done it. Most of the developers I know have done it, too.
The frustrating part is that these bugs are rarely exotic. They are small, common habits that look fine in a code review, pass a quick manual test, and then fail at 2 a.m. when real users show up with real data.
AI coding assistants have made this a little trickier. They write code fast, and it usually looks great. But they repeat the same old mistakes found in the code they learned from, and they sometimes invent APIs that do not exist. Speed without review just means you ship bugs faster.
Here are 30 mistakes I see over and over, each with a short snippet showing the problem and a better way. Skim the ones you know, and be honest about the ones you do not.
1. Using == instead of ===
Loose equality converts types behind your back, and the results are surprising.
// Risky
if (userId == 0) { /* also true for '', '0', and false */ }
// Better
if (userId === 0) { /* only true for the number 0 */ }
// Risky
if (userId == 0) { /* also true for '', '0', and false */ }
// Better
if (userId === 0) { /* only true for the number 0 */ }
2. Using var in loops with async callbacks
var is function-scoped, so every callback shares the same variable.
<button data-code="// Prints 3, 3, 3
for (var i = 0; i console.log(i), 0);
}
// Prints 0, 1, 2
for (let i = 0; i console.log(i), 0);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// Prints 3, 3, 3
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// Prints 0, 1, 2
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// Prints 3, 3, 3
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// Prints 0, 1, 2
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
3. Forgetting await
Without await, you get a pending Promise instead of your data. It is one of the most common AI-generated slip-ups, too.
// Bug: user is a Promise, so user.name is undefined
const user = getUser(id);
console.log(user.name);
// Fix
const user = await getUser(id);
console.log(user.name);
// Bug: user is a Promise, so user.name is undefined
const user = getUser(id);
console.log(user.name);
// Fix
const user = await getUser(id);
console.log(user.name);
4. Using async callbacks inside forEach
forEach does not wait for Promises. Your code moves on before the work is done.
{
await save(item);
});
console.log('Done');
// Fix
for (const item of items) {
await save(item);
}
console.log('Done');” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// Bug: 'Done' prints before any save finishes
items.forEach(async (item) => {
await save(item);
});
console.log('Done');
// Fix
for (const item of items) {
await save(item);
}
console.log('Done');
// Bug: 'Done' prints before any save finishes
items.forEach(async (item) => {
await save(item);
});
console.log('Done');
// Fix
for (const item of items) {
await save(item);
}
console.log('Done');
5. Leaving Promise rejections unhandled
An unhandled rejection can crash a Node process or fail silently in the browser.
console.log('Sent'));
// Better
try {
await sendEmail(user);
} catch (err) {
logger.error('Email failed', { userId: user.id, err });
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// Risky
sendEmail(user).then(() => console.log('Sent'));
// Better
try {
await sendEmail(user);
} catch (err) {
logger.error('Email failed', { userId: user.id, err });
}
// Risky
sendEmail(user).then(() => console.log('Sent'));
// Better
try {
await sendEmail(user);
} catch (err) {
logger.error('Email failed', { userId: user.id, err });
}
6. Awaiting independent tasks one by one
If two requests do not depend on each other, do not make them wait in line.
// Slow: about 2 seconds total
const profile = await getProfile(id); // 1s
const orders = await getOrders(id); // 1s
// Faster: about 1 second total
const [profile, orders] = await Promise.all([
getProfile(id),
getOrders(id),
]);
// Slow: about 2 seconds total
const profile = await getProfile(id); // 1s
const orders = await getOrders(id); // 1s
// Faster: about 1 second total
const [profile, orders] = await Promise.all([
getProfile(id),
getOrders(id),
]);
7. Mutating function arguments
Changing an object you were handed creates side effects that are painful to trace.
// Risky: changes the caller's object
function applyDiscount(order) {
order.total = order.total * 0.9;
return order;
}
// Better: returns a new object
function applyDiscount(order) {
return { ...order, total: order.total * 0.9 };
}
// Risky: changes the caller's object
function applyDiscount(order) {
order.total = order.total * 0.9;
return order;
}
// Better: returns a new object
function applyDiscount(order) {
return { ...order, total: order.total * 0.9 };
}
8. Thinking the spread operator makes a deep copy
Spread only copies one level. Nested objects are still shared.
const original = { name: 'Ava', address: { city: 'Austin' } };
const copy = { ...original };
copy.address.city = 'Denver';
console.log(original.address.city); // 'Denver' (surprise)
// Fix
const safeCopy = structuredClone(original);
const original = { name: 'Ava', address: { city: 'Austin' } };
const copy = { ...original };
copy.address.city = 'Denver';
console.log(original.address.city); // 'Denver' (surprise)
// Fix
const safeCopy = structuredClone(original);
9. Trusting floating-point math with money
Computers cannot represent some decimals exactly.
console.log(0.1 + 0.2); // 0.30000000000000004
// Better: work in cents
const totalCents = 10 + 20;
const total = (totalCents / 100).toFixed(2); // '0.30'
console.log(0.1 + 0.2); // 0.30000000000000004
// Better: work in cents
const totalCents = 10 + 20;
const total = (totalCents / 100).toFixed(2); // '0.30'
10. Using parseInt without thinking
parseInt happily accepts garbage and stops at the first bad character.
parseInt('42px'); // 42 (probably not what you wanted)
parseInt(''); // NaN
// Stricter
Number('42px'); // NaN, so you can catch it
Number('42'); // 42
parseInt('42px'); // 42 (probably not what you wanted)
parseInt(''); // NaN
// Stricter
Number('42px'); // NaN, so you can catch it
Number('42'); // 42
11. Using || for defaults when 0 or ” is valid
|| treats every falsy value as missing. ?? only treats null and undefined as missing.
const quantity = 0;
// Bug: returns 1
const qty = quantity || 1;
// Fix: returns 0
const qty2 = quantity ?? 1;
const quantity = 0;
// Bug: returns 1
const qty = quantity || 1;
// Fix: returns 0
const qty2 = quantity ?? 1;
12. Skipping optional chaining on uncertain data
“Cannot read properties of undefined” is probably the most common production error in JavaScript.
// Crashes if profile or address is missing
const city = user.profile.address.city;
// Safer
const city = user?.profile?.address?.city ?? 'Unknown';
// Crashes if profile or address is missing
const city = user.profile.address.city;
// Safer
const city = user?.profile?.address?.city ?? 'Unknown';
13. Calling sort() on numbers without a comparator
By default, sort() compares values as strings.
a – b); // [1, 9, 10, 100]” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
[10, 9, 1, 100].sort(); // [1, 10, 100, 9]
[10, 9, 1, 100].sort((a, b) => a - b); // [1, 9, 10, 100]
[10, 9, 1, 100].sort(); // [1, 10, 100, 9]
[10, 9, 1, 100].sort((a, b) => a - b); // [1, 9, 10, 100]
14. Checking for NaN with equality
NaN is not equal to anything, including itself.
const value = Number('abc');
value === NaN; // always false
Number.isNaN(value); // true
const value = Number('abc');
value === NaN; // always false
Number.isNaN(value); // true
15. Losing this in callbacks
Pass a method around and it forgets which object it belongs to.
c.increment(), 100); // works” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
class Counter {
count = 0;
increment() { this.count++; }
}
const c = new Counter();
setTimeout(c.increment, 100); // 'this' is lost
setTimeout(() => c.increment(), 100); // works
class Counter {
count = 0;
increment() { this.count++; }
}
const c = new Counter();
setTimeout(c.increment, 100); // 'this' is lost
setTimeout(() => c.increment(), 100); // works
16. Never removing event listeners
Forgotten listeners keep objects alive and slowly leak memory, especially in single-page apps.
function onResize() { /* ... */ }
window.addEventListener('resize', onResize);
// Later, when the component goes away
window.removeEventListener('resize', onResize);
function onResize() { /* ... */ }
window.addEventListener('resize', onResize);
// Later, when the component goes away
window.removeEventListener('resize', onResize);
17. Using for...in on arrays
for...in loops over keys (as strings), including inherited ones.
const nums = [10, 20, 30];
for (const i in nums) console.log(typeof i); // 'string'
for (const n of nums) console.log(n); // 10, 20, 30
const nums = [10, 20, 30];
for (const i in nums) console.log(typeof i); // 'string'
for (const n of nums) console.log(n); // 10, 20, 30
18. Calling JSON.parse without protection
One malformed string and your whole request handler throws.
// Risky
const data = JSON.parse(rawInput);
// Safer
function safeParse(text, fallback = null) {
try {
return JSON.parse(text);
} catch {
return fallback;
}
}
// Risky
const data = JSON.parse(rawInput);
// Safer
function safeParse(text, fallback = null) {
try {
return JSON.parse(text);
} catch {
return fallback;
}
}
19. Ignoring time zones with dates
A date string without a time zone can shift by a day depending on where the code runs.
// Parsed as UTC, may display as the previous day in the U.S.
new Date('2026-03-01').toLocaleDateString('en-US');
// Be explicit
new Date('2026-03-01').toLocaleDateString('en-US', { timeZone: 'UTC' });
// Parsed as UTC, may display as the previous day in the U.S.
new Date('2026-03-01').toLocaleDateString('en-US');
// Be explicit
new Date('2026-03-01').toLocaleDateString('en-US', { timeZone: 'UTC' });
20. Assuming fetch throws on 404 or 500
fetch only rejects on network failure. HTTP errors still resolve.
const res = await fetch('/api/users');
if (!res.ok) {
throw new Error(`Request failed: ${res.status}`);
}
const users = await res.json();
const res = await fetch('/api/users');
if (!res.ok) {
throw new Error(`Request failed: ${res.status}`);
}
const users = await res.json();
21. Filling an array with one shared object
Every slot points to the same reference.
[]);” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
const grid = new Array(3).fill([]);
grid[0].push('x');
console.log(grid); // [['x'], ['x'], ['x']]
const safeGrid = Array.from({ length: 3 }, () => []);
const grid = new Array(3).fill([]);
grid[0].push('x');
console.log(grid); // [['x'], ['x'], ['x']]
const safeGrid = Array.from({ length: 3 }, () => []);
22. Modifying an array while looping over it
Removing items mid-loop shifts the indexes and skips elements.
<button data-code="// Bug: skips items
for (let i = 0; i !item.done);” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// Bug: skips items
for (let i = 0; i < list.length; i++) {
if (list[i].done) list.splice(i, 1);
}
// Fix
const active = list.filter((item) => !item.done);
// Bug: skips items
for (let i = 0; i < list.length; i++) {
if (list[i].done) list.splice(i, 1);
}
// Fix
const active = list.filter((item) => !item.done);
23. Firing expensive work on every keystroke
Search boxes and resize handlers can trigger hundreds of calls per second.
{
clearTimeout(timer);
timer = setTimeout(() => fn(…args), delay);
};
}
input.addEventListener('input', debounce(search, 300));” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
function debounce(fn, delay = 300) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
input.addEventListener('input', debounce(search, 300));
function debounce(fn, delay = 300) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
input.addEventListener('input', debounce(search, 300));
24. Blocking the event loop
One heavy synchronous task freezes the UI, or every other request on your Node server.
<button data-code="// Blocks everything while it runs
const result = hugeArray.map(expensiveCalc);
// Better: process in chunks and yield
async function processInChunks(items, size = 500) {
for (let i = 0; i setTimeout(r, 0));
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// Blocks everything while it runs
const result = hugeArray.map(expensiveCalc);
// Better: process in chunks and yield
async function processInChunks(items, size = 500) {
for (let i = 0; i < items.length; i += size) {
items.slice(i, i + size).forEach(expensiveCalc);
await new Promise((r) => setTimeout(r, 0));
}
}
// Blocks everything while it runs
const result = hugeArray.map(expensiveCalc);
// Better: process in chunks and yield
async function processInChunks(items, size = 500) {
for (let i = 0; i < items.length; i += size) {
items.slice(i, i + size).forEach(expensiveCalc);
await new Promise((r) => setTimeout(r, 0));
}
}
25. Writing empty catch blocks
Swallowing errors is how a small bug turns into a mystery.
// Bad: the failure disappears
try { await chargeCard(order); } catch (e) {}
// Better
try {
await chargeCard(order);
} catch (err) {
logger.error('Charge failed', { orderId: order.id, err });
throw err;
}
// Bad: the failure disappears
try { await chargeCard(order); } catch (e) {}
// Better
try {
await chargeCard(order);
} catch (err) {
logger.error('Charge failed', { orderId: order.id, err });
throw err;
}
26. Putting user input into innerHTML
This is a classic cross-site scripting (XSS) hole.
// Dangerous
comment.innerHTML = userInput;
// Safe
comment.textContent = userInput;
// Dangerous
comment.innerHTML = userInput;
// Safe
comment.textContent = userInput;
27. Validating only on the client
Browser checks improve the experience, but anyone can bypass them. The server must validate too.
{
const { email, age } = req.body;
if (typeof email !== 'string' || !email.includes('@')) {
return res.status(400).json({ error: 'Invalid email' });
}
if (!Number.isInteger(age) || age
app.post('/signup', (req, res) => {
const { email, age } = req.body;
if (typeof email !== 'string' || !email.includes('@')) {
return res.status(400).json({ error: 'Invalid email' });
}
if (!Number.isInteger(age) || age < 13) {
return res.status(400).json({ error: 'Invalid age' });
}
// continue...
});
app.post('/signup', (req, res) => {
const { email, age } = req.body;
if (typeof email !== 'string' || !email.includes('@')) {
return res.status(400).json({ error: 'Invalid email' });
}
if (!Number.isInteger(age) || age < 13) {
return res.status(400).json({ error: 'Invalid age' });
}
// continue...
});
28. Comparing objects and arrays by reference
Two objects with identical content are still two different objects.
({ a: 1 }) === ({ a: 1 }); // false
[1, 2] === [1, 2]; // false
// Simple deep check (fine for plain JSON-like data)
JSON.stringify(a) === JSON.stringify(b);
({ a: 1 }) === ({ a: 1 }); // false
[1, 2] === [1, 2]; // false
// Simple deep check (fine for plain JSON-like data)
JSON.stringify(a) === JSON.stringify(b);
29. Shipping secrets in frontend code
Anything in your browser bundle is public, even if it is “hidden” in an environment variable.
// Exposed to every visitor
const client = new PaymentClient('sk_live_abc123');
// Keep the secret on the server and expose a safe endpoint
const res = await fetch('/api/create-payment', { method: 'POST' });
// Exposed to every visitor
const client = new PaymentClient('sk_live_abc123');
// Keep the secret on the server and expose a safe endpoint
const res = await fetch('/api/create-payment', { method: 'POST' });
30. Trusting AI-generated code without reading it
AI tools are great at drafts. They are also great at confidently using methods that do not exist, or that your runtime does not support yet.
// Looks plausible, but arrays have no .flatten() method
const flat = nested.flatten();
// The real method
const flat = nested.flat();
// Also check browser and Node support before using newer APIs,
// such as Object.groupBy or Array.prototype.toSorted.
// Looks plausible, but arrays have no .flatten() method
const flat = nested.flatten();
// The real method
const flat = nested.flat();
// Also check browser and Node support before using newer APIs,
// such as Object.groupBy or Array.prototype.toSorted.
My rule: treat AI output like a pull request from a smart but very new teammate. Read it, run it, test the edge cases, and ask what happens with empty, null, and huge inputs.
A quick checklist before you ship
- Did I use === and ?? where they matter?
- Is every Promise awaited and every error handled?
- Could this data be
null,undefined, or empty? - Am I mutating something I do not own?
- Is user input validated on the server and escaped on output?
- Did I actually run the AI-generated code against edge cases?
Final thoughts
Nobody avoids all of these mistakes. Experienced developers just make them less often, catch them faster, and build habits like linting, tests, and code review to cover the gaps.
Turn on ESLint with strict rules, add TypeScript if you can, and write a test for the weird case you just thought of. Future you, at 2 a.m., will be grateful.
If this helped, share it with a teammate. Which of these has bitten you the hardest? I would love to hear about it in the comments.


