Common JavaScript Mistakes
Most JavaScript bugs aren't exotic. They are the same few mistakes, made again and again by beginners and experienced developers alike: a string added to a number, a lost this, a forgotten await, a shared array changed by accident. This lesson collects the 20 most common, grouped by area. Each one runs here and shows the real wrong result, followed by the fix and the lesson that explains the underlying rule. Use it as a checklist when debugging and when reviewing code.
In One Minute
- Types:
+joining strings,==,NaNchecks, floating-point money,typeof null. - Variables and scope:
varin loops, missing declarations,constobjects changed. - Objects and arrays: shared references, default
sort, mutating while iterating,for...inon arrays. - Functions and
this: lostthis, arrow methods, missingreturn. - Async: forgotten
await,forEachwithasync, unhandled rejections, uncheckedfetchresponses. - DOM:
innerHTMLwith user data, scripts that run before the DOM exists.
Types and Values
1. Adding Strings Instead of Numbers
const fromForm = "120";
console.log(fromForm + 30, Number(fromForm) + 30);12030 150Fix: convert input with Number() where it enters the program. See "Arithmetic and Assignment Operators".
2. Using ==
console.log(0 == "", "0" == false, null == 0, 0 === "", "0" === false);true true false false falseFix: always use === and !==. See "Comparison Operators".
3. Testing for NaN with ===
const amount = Number("abc");
console.log(amount === NaN, Number.isNaN(amount));false trueFix: Number.isNaN(x), or Number.isFinite(x) to require a usable number. See "Numbers".
4. Floating-Point Money
console.log(0.1 + 0.2, 19.99 * 3, 1999 * 3 / 100);0.30000000000000004 59.97 59.9719.99 * 3 happens to look right here, but sums of many decimal amounts drift. Fix: store integer cents and format only for display. See "Numbers".
5. typeof for Arrays and null
console.log(typeof [], typeof null, Array.isArray([]), null === null);object object true trueFix: Array.isArray(x) and x === null. See "Checking Types".
6. Treating 0 and "" as Missing
const balance = 0;
console.log(balance || "no balance", balance ?? "no balance");no balance 0Fix: ?? for defaults, explicit comparisons for numbers. See "Logical Operators".
Variables and Scope
7. var in Loops with Callbacks
const withVar = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);
const withLet = [];
for (let j = 0; j < 3; j++) withLet.push(() => j);
console.log(withVar.map((f) => f()), withLet.map((f) => f()));[3, 3, 3] [0, 1, 2]Fix: let (or const in for...of). See "Closures".
8. Thinking const Freezes Objects
const settings = { currency: "USD" };
settings.currency = "EUR";
console.log(settings.currency);EURFix: const only stops reassignment; use Object.freeze to stop changes. See "Protecting Objects".
Objects and Arrays
9. Shared References
const defaults = { tags: [] };
const a = { ...defaults };
const b = { ...defaults };
a.tags.push("late");
console.log(b.tags);['late']Spread copies only the top level; both objects share one tags array. Fix: copy nested values (tags: [...defaults.tags]) or use structuredClone. See "Copying and Comparing Objects".
10. Sorting Without a Compare Function
console.log([10, 9, 100, 1].sort(), [10, 9, 100, 1].sort((a, b) => a - b));[1, 10, 100, 9] [1, 9, 10, 100]Fix: always pass a compare function. See "Sorting Arrays".
11. sort Changing the Original
const fees = [120, 45, 85];
const sorted = fees.sort((a, b) => a - b);
console.log(fees, sorted === fees);[45, 85, 120] trueFix: toSorted (or copy first) when the array is shared. See "Sorting Arrays".
12. Removing Items While Looping Forward
const amounts = [0, 0, 85, 0];
for (let i = 0; i < amounts.length; i++) if (amounts[i] === 0) amounts.splice(i, 1);
console.log(amounts, [0, 0, 85, 0].filter((a) => a !== 0));[0, 85] [85]Fix: build a new array with filter (or loop backward). See "Adding and Removing Array Items".
13. for...in on Arrays
let total = 0;
for (const i in [120, 85]) total += i;
console.log(total);001Fix: for...of for values. See "The for...of and for...in Loops".
Functions and this
14. Losing this in Callbacks
"use strict";
const account = { owner: "Navika", describe() { return this?.owner; } };
const run = (fn) => fn();
console.log(run(account.describe), run(() => account.describe()));undefined NavikaFix: wrap in an arrow or use bind. See "The This Keyword".
15. Arrow Functions as Methods
const student = { firstName: "Advitha", hello: () => `Hi ${this?.firstName}`, hi() { return `Hi ${this.firstName}`; } };
console.log(student.hello(), "|", student.hi());Hi undefined | Hi AdvithaFix: method shorthand for methods. See "Arrow Functions".
16. Missing return
const doubled = [1, 2].map((n) => { n * 2; });
const objects = [1, 2].map((n) => { id: n });
console.log(doubled, objects);[undefined, undefined] [undefined, undefined]Fix: (n) => n * 2, and wrap object literals: (n) => ({ id: n }). See "Arrow Functions".
Asynchronous Code
17. Forgetting await
async function getBalance() { return 120; }
const balance = getBalance();
console.log(typeof balance, balance + 30);object [object Promise]30Fix: await getBalance(). See "Async Mistakes and Debugging".
18. forEach with async
const saved = [];
[1, 2, 3].forEach(async (id) => { await null; saved.push(id); });
console.log("saved so far:", saved.length);saved so far: 0Fix: for...of with await, or await Promise.all(items.map(...)). See "Async Mistakes and Debugging".
19. Not Checking response.ok
const response = new Response("Not found", { status: 404 });
console.log(response.ok, await response.text());false Not foundfetch resolves even for 404 and 500; parsing that body as data fails later in confusing ways. Fix: if (!response.ok) throw new Error(...). See "Fetch API".
The DOM
20. innerHTML with User Data
<p id="welcome"></p>
<script>
const name = '<img src="x" onerror="console.log(\'injected code ran\')">';
document.querySelector("#welcome").innerHTML = `Hi ${name}`;
</script>injected code ranFix: textContent, or createElement with textContent. See "Changing Content and Styles" and "Browser Security".
Tools That Catch Them
| Mistakes | Caught by |
|---|---|
==, var, unused variables, missing return in callbacks | ESLint (eqeqeq, no-var, array-callback-return) |
Forgotten await, floating promises, wrong types | TypeScript with typescript-eslint (no-floating-promises) |
| String/number mix-ups, missing properties | TypeScript |
innerHTML with variables | ESLint security plugins, Trusted Types (in supporting browsers), code review |
| Edge cases in logic | Unit tests with node:test |
In Practice
A Fee Tracker bug report: "the dashboard total is $12030 and the list sometimes misses students". Five mistakes from this page were involved, all fixed below:
async function loadStudents() {
return [{ name: "Srihitha", balance: "85" }, { name: "Navika", balance: 0 }, { name: "Advitha", balance: "45" }];
}
const students = (await loadStudents()).map((s) => ({ ...s, balance: Number(s.balance) }));
const total = students.reduce((sum, s) => sum + s.balance, 0);
const owing = students.filter((s) => s.balance > 0).toSorted((a, b) => b.balance - a.balance);
console.log(`Total due: $${total}`);
console.log(owing.map((s) => s.name), students.length);Total due: $130
['Srihitha', 'Advitha'] 3The fixes: await the data (17), convert balances to numbers (1), use reduce with a starting 0, filter instead of splicing in a loop (12), and toSorted with a compare function (10, 11).
Common Mistakes
This whole lesson is a list of them. The most important single habit: when a value looks wrong, check its type first (typeof, Array.isArray), since most of these bugs are type confusion.
Practice
Challenge: This function has three mistakes from this page. Fix them so it returns the two largest numeric amounts from form strings, largest first, without changing the input array.
function topTwo(inputs) {
const amounts = inputs.sort();
return amounts.slice(-2);
}Show solution
function topTwo(inputs) {
return inputs.map(Number).filter(Number.isFinite).toSorted((a, b) => b - a).slice(0, 2);
}
const fromForm = ["120", "9", "450", "abc", "85"];
console.log(topTwo(fromForm), fromForm.length);[450, 120] 5The original sorted strings (so "9" beat "450"), changed the caller's array, and kept invalid values.
Key Takeaways
| # | Mistake | Fix |
|---|---|---|
| 1 | "120" + 30 | Number("120") + 30 |
| 2 | == | === |
| 10 | .sort() on numbers | .sort((a, b) => a - b) |
| 14 | run(obj.method) | run(() => obj.method()) |
| 17 | Missing await | await fn() |
| 20 | innerHTML = userText | textContent = userText |
Was this tutorial helpful?