Common JavaScript Mistakes

Updated · 8 min read
mediumES2026javascriptmistakesdebugging

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, ==, NaN checks, floating-point money, typeof null.
  • Variables and scope: var in loops, missing declarations, const objects changed.
  • Objects and arrays: shared references, default sort, mutating while iterating, for...in on arrays.
  • Functions and this: lost this, arrow methods, missing return.
  • Async: forgotten await, forEach with async, unhandled rejections, unchecked fetch responses.
  • DOM: innerHTML with user data, scripts that run before the DOM exists.

Types and Values

1. Adding Strings Instead of Numbers

m1.js▶ Try it
const fromForm = "120";
console.log(fromForm + 30, Number(fromForm) + 30);
Output
12030 150

Fix: convert input with Number() where it enters the program. See "Arithmetic and Assignment Operators".

2. Using ==

m2.js▶ Try it
console.log(0 == "", "0" == false, null == 0, 0 === "", "0" === false);
Output
true true false false false

Fix: always use === and !==. See "Comparison Operators".

3. Testing for NaN with ===

m3.js▶ Try it
const amount = Number("abc");
console.log(amount === NaN, Number.isNaN(amount));
Output
false true

Fix: Number.isNaN(x), or Number.isFinite(x) to require a usable number. See "Numbers".

4. Floating-Point Money

m4.js▶ Try it
console.log(0.1 + 0.2, 19.99 * 3, 1999 * 3 / 100);
Output
0.30000000000000004 59.97 59.97

19.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

m5.js▶ Try it
console.log(typeof [], typeof null, Array.isArray([]), null === null);
Output
object object true true

Fix: Array.isArray(x) and x === null. See "Checking Types".

6. Treating 0 and "" as Missing

m6.js▶ Try it
const balance = 0;
console.log(balance || "no balance", balance ?? "no balance");
Output
no balance 0

Fix: ?? for defaults, explicit comparisons for numbers. See "Logical Operators".

Variables and Scope

7. var in Loops with Callbacks

m7.js▶ Try it
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()));
Output
[3, 3, 3] [0, 1, 2]

Fix: let (or const in for...of). See "Closures".

8. Thinking const Freezes Objects

m8.js▶ Try it
const settings = { currency: "USD" };
settings.currency = "EUR";
console.log(settings.currency);
Output
EUR

Fix: const only stops reassignment; use Object.freeze to stop changes. See "Protecting Objects".

Objects and Arrays

9. Shared References

m9.js▶ Try it
const defaults = { tags: [] };
const a = { ...defaults };
const b = { ...defaults };
a.tags.push("late");
console.log(b.tags);
Output
['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

m10.js▶ Try it
console.log([10, 9, 100, 1].sort(), [10, 9, 100, 1].sort((a, b) => a - b));
Output
[1, 10, 100, 9] [1, 9, 10, 100]

Fix: always pass a compare function. See "Sorting Arrays".

11. sort Changing the Original

m11.js▶ Try it
const fees = [120, 45, 85];
const sorted = fees.sort((a, b) => a - b);
console.log(fees, sorted === fees);
Output
[45, 85, 120] true

Fix: toSorted (or copy first) when the array is shared. See "Sorting Arrays".

12. Removing Items While Looping Forward

m12.js▶ Try it
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));
Output
[0, 85] [85]

Fix: build a new array with filter (or loop backward). See "Adding and Removing Array Items".

13. for...in on Arrays

m13.js▶ Try it
let total = 0;
for (const i in [120, 85]) total += i;
console.log(total);
Output
001

Fix: for...of for values. See "The for...of and for...in Loops".

Functions and this

14. Losing this in Callbacks

m14.js▶ Try it
"use strict";
const account = { owner: "Navika", describe() { return this?.owner; } };
const run = (fn) => fn();
console.log(run(account.describe), run(() => account.describe()));
Output
undefined Navika

Fix: wrap in an arrow or use bind. See "The This Keyword".

15. Arrow Functions as Methods

m15.js▶ Try it
const student = { firstName: "Advitha", hello: () => `Hi ${this?.firstName}`, hi() { return `Hi ${this.firstName}`; } };
console.log(student.hello(), "|", student.hi());
Output
Hi undefined | Hi Advitha

Fix: method shorthand for methods. See "Arrow Functions".

16. Missing return

m16.js▶ Try it
const doubled = [1, 2].map((n) => { n * 2; });
const objects = [1, 2].map((n) => { id: n });
console.log(doubled, objects);
Output
[undefined, undefined] [undefined, undefined]

Fix: (n) => n * 2, and wrap object literals: (n) => ({ id: n }). See "Arrow Functions".

Asynchronous Code

17. Forgetting await

m17.js▶ Try it
async function getBalance() { return 120; }
const balance = getBalance();
console.log(typeof balance, balance + 30);
Output
object [object Promise]30

Fix: await getBalance(). See "Async Mistakes and Debugging".

18. forEach with async

m18.js▶ Try it
const saved = [];
[1, 2, 3].forEach(async (id) => { await null; saved.push(id); });
console.log("saved so far:", saved.length);
Output
saved so far: 0

Fix: for...of with await, or await Promise.all(items.map(...)). See "Async Mistakes and Debugging".

19. Not Checking response.ok

m19.js▶ Try it
const response = new Response("Not found", { status: 404 });
console.log(response.ok, await response.text());
Output
false Not found

fetch 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

m20.html
<p id="welcome"></p>
<script>
  const name = '<img src="x" onerror="console.log(\'injected code ran\')">';
  document.querySelector("#welcome").innerHTML = `Hi ${name}`;
</script>
Output
injected code ran

Fix: textContent, or createElement with textContent. See "Changing Content and Styles" and "Browser Security".

Tools That Catch Them

MistakesCaught by
==, var, unused variables, missing return in callbacksESLint (eqeqeq, no-var, array-callback-return)
Forgotten await, floating promises, wrong typesTypeScript with typescript-eslint (no-floating-promises)
String/number mix-ups, missing propertiesTypeScript
innerHTML with variablesESLint security plugins, Trusted Types (in supporting browsers), code review
Edge cases in logicUnit 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:

fixed-dashboard.js▶ Try it
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);
Output
Total due: $130
['Srihitha', 'Advitha'] 3

The 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.

practice.js
function topTwo(inputs) {
  const amounts = inputs.sort();
  return amounts.slice(-2);
}
Show solution
practice-solution.js▶ Try it
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);
Output
[450, 120] 5

The original sorted strings (so "9" beat "450"), changed the caller's array, and kept invalid values.

Quick check: Common mistakes

3 questions
1What does "5" + 3 produce?
2What does [10, 9, 100].sort() return?
3What is the safe way to insert a user's name into the page?

Key Takeaways

#MistakeFix
1"120" + 30Number("120") + 30
2=====
10.sort() on numbers.sort((a, b) => a - b)
14run(obj.method)run(() => obj.method())
17Missing awaitawait fn()
20innerHTML = userTexttextContent = userText

Was this tutorial helpful?

Lesson 123 of 139