← Back to JavaScript Course | Chapter 12: Reference & Interview | Lesson 4 of 9

JS Common Mistakes

Assignment vs Comparison

= assigns a value while == or === compares one; accidentally writing if (x = 5) inside a condition silently assigns 5 to x and always evaluates truthy, a classic hard-to-spot bug.

Example: Assignment vs Comparison

javascript
let x = 0;
if (x = 5) { // mistake: assignment instead of comparison
  console.log("Always runs, x is now", x);
}

Variable Scope Mistakes

Declaring a variable with var inside a loop or block doesn't scope it the way let does, which can lead to every closure in a loop capturing the same final value instead of its own.

Example: Variable Scope Mistakes

javascript
var funcs = [];
for (var i = 0; i < 3; i++) {
  funcs.push(() => console.log(i));
}
funcs[0](); // 3, not 0 - var is not block-scoped

Array and Object Mistakes

Mutating an array or object you didn't mean to change — for example, calling .sort() (which mutates in place) when you intended to keep the original order — is a frequent source of subtle bugs.

Example: Array and Object Mistakes

javascript
const original = [3, 1, 2];
const sorted = original.sort(); // mutates in place!
console.log(original); // [1, 2, 3] - original changed too

Async and Function Mistakes

Forgetting to await a Promise, or mixing .then() chains with async/await inconsistently, can cause code to run out of order or silently swallow an error the catch block never sees.

Example: Async and Function Mistakes

javascript
async function getData() {
  const result = fetchData(); // forgot await
  console.log(result); // logs a Promise, not the resolved value
}
function fetchData() { return Promise.resolve(42); }
getData();

Type and Conversion Mistakes

Comparing values with == instead of === can trigger unexpected type coercion (like '' == 0 being true), while assuming typeof null is object misdirects some type-checking logic.

Example: Type and Conversion Mistakes

javascript
console.log('' == 0);          // true - unexpected coercion with ==
console.log(typeof null);      // "object" - a long-standing quirk
🔒

Chapter Quiz — Complete all 9 topics to unlock

0/9 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.