5 Common JavaScript Mistakes
JavaScript is one of the easiest languages to start with, but it also has a few tricky parts that trip up beginners. Here are 5 common mistakes and how to avoid them.
1. Using == Instead of ===:
Many beginners use ==to compare values, but this can cause unexpected bugs because == converts types before comparing, while === checks both value and type.
Example:
console.log(0 == "0"); // true (bad — different types treated as equal)
console.log(0 === "0"); // false (correct — strict comparison)
2.Confusing var, let, and const:
Beginners often use var everywhere out of habit, without realizing it behaves differently from let and const. var is function-scoped and can be redeclared, which often leads to bugs in loops and conditionals.
Example:
var x = 10;
var x = 20; // no error, silently overwritten
let y = 10;
let y = 20; // Error: cannot redeclare
3. Misusing async/await and Promises:
A common mistake is forgetting to use await, which causes your code to run before the data actually arrives.
Example:
Wrong method:
function getData() {
const data = fetch("/api/data"); // missing await
console.log(data); // logs a Promise, not the actual data
}
Correct method:
async function getData() {
const data = await fetch("/api/data");
const result = await data.json();
console.log(result);
}
4. Not Understanding Hoisting:
Beginners are often confused when a variable seems to exist before it's even declared. This happens because of hoisting — JavaScript moves variable and function declarations to the top of their scope before running the code.
Example:
console.log(a); // undefined (not an error!)
var a = 5;
console.log(b); // Error: Cannot access 'b' before initialization
let b = 5;
console.log(a); // undefined (not an error!)
var a = 5;
console.log(b); // Error: Cannot access 'b' before initialization
let b = 5;
5. Accidentally Mutating Arrays and Objects:
Beginners often modify arrays or objects directly, not realizing that in JavaScript, objects and arrays are copied by reference, not by value. This means changing a "copy" can accidentally change the original.
Example:
const original = [1, 2, 3];
const copy = original; // NOT a real copy — same reference
copy.push(4);
console.log(original); // [1, 2, 3, 4] — original got changed too!
To make a real copy, use the spread operator or array/object methods:
const properCopy = [...original]; // real copy
properCopy.push(5);
console.log(original); // [1, 2, 3, 4] — unaffected
console.log(properCopy); // [1, 2, 3, 4, 5]
Conclusion:
These 5 mistakes are extremely common when learning JavaScript, but once you understand why they happen, they're easy to avoid. Practicing with small examples like these will make your code more reliable and bug-free.
Top comments (0)