Common Errors in JavaScript (And How to Avoid Them)

JavaScript is one of the most powerful and widely used programming languages in web development. Its flexibility and ease of use are among its strengths—but that flexibility often leads to confusion, bugs, and hard-to-diagnose errors, especially for beginners. In this post, we’ll explore the most common JavaScript errors, why they happen, and how to avoid or fix them. Whether you're new to JS or an experienced developer, understanding these mistakes can help you write cleaner, bug-free code. I. Undefined vs. Null Confusion The Error: let user = undefined; if (user === null) { console.log("No user"); } What’s wrong? undefined means a variable has been declared but not assigned a value, while null is a value that represents "no value". Using them interchangeably causes bugs. Fix: Use strict equality checks when needed, and ensure you initialize variables appropriately: if (user == null) { // checks for both null and undefined console.log("No user"); } II. Forgetting let, const, or var The Error: x = 10; What’s wrong? This creates a global variable unintentionally, which can lead to unexpected behavior or conflicts. Fix: Always declare your variables properly: let x = 10; // or const x = 10; III. Incorrect Use of 'this' The Error: const user = { name: "Jane", greet: function () { setTimeout(function () { console.log(Hi, I'm ${this.name}); }, 1000); } }; user.greet(); // Outputs: "Hi, I'm undefined" Why it happens: In the setTimeout function, this doesn’t refer to user but to the global object. Fix: Use an arrow function to preserve this: setTimeout(() => { console.log(Hi, I'm ${this.name}); }, 1000); IV. Misunderstanding Asynchronous Behavior The Error: let data = fetch("https://api.example.com/data"); console.log(data); // Promise { } Why it happens: fetch() returns a promise, and JavaScript doesn’t wait for it unless you tell it to. Fix: Use async/await: async function getData() { const response = await fetch("https://api.example.com/data"); const data = await response.json(); console.log(data); } getData(); V. Not Handling Errors in Promises The Error: fetch("https://api.example.com/data") .then(response => response.json()) .then(data => console.log(data)); What’s missing? There's no error handling. If something goes wrong, you won’t know. Fix: Always handle rejections: fetch("https://api.example.com/data") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error("Error fetching data:", error)); VI. Using = Instead of == or === The Error: if (a = 5) { // This will always be true! } Why it happens: The single = is an assignment, not a comparison. Fix: Use === for strict comparison: if (a === 5) { // correct } VII. Modifying Objects or Arrays Directly The Error: const arr = [1, 2, 3]; const newArr = arr; newArr.push(4); console.log(arr); // [1, 2, 3, 4] What’s wrong? Both variables reference the same array in memory. Fix: Use spread syntax to copy: const newArr = [...arr]; VIII. Looping with var Instead of let The Error: for (var i = 0; i < 5; i++) { setTimeout(() => console.log(i), 1000); } // Logs: 5, 5, 5, 5, 5 Fix: let has block scope: for (let i = 0; i < 5; i++) { setTimeout(() => console.log(i), 1000); } // Logs: 0, 1, 2, 3, 4 IX. Not Using const for Constants Using let for values that never change can lead to accidental reassignments. Fix: Use const for values that don't change: const PI = 3.14159; X. DOM Not Ready Before Script Execution The Error: document.getElementById("btn").addEventListener("click", () => {}); // Error if the script runs before DOM is ready Fix: Place your at the bottom of the HTML file or wrap it in a DOM-ready event: document.addEventListener("DOMContentLoaded", () => { document.getElementById("btn").addEventListener("click", () => {}); }); Conclusion: JavaScript errors are often easy to make but just as easy to avoid once you understand the language’s quirks. By learning these common mistakes and practicing clean, intentional coding habits, you’ll be on your way to writing more robust and error-free JavaScript.

May 12, 2025 - 12:57
 0
Common Errors in JavaScript (And How to Avoid Them)

JavaScript is one of the most powerful and widely used programming languages in web development. Its flexibility and ease of use are among its strengths—but that flexibility often leads to confusion, bugs, and hard-to-diagnose errors, especially for beginners.

In this post, we’ll explore the most common JavaScript errors, why they happen, and how to avoid or fix them. Whether you're new to JS or an experienced developer, understanding these mistakes can help you write cleaner, bug-free code.

I. Undefined vs. Null Confusion

The Error:

let user = undefined;
if (user === null) {
console.log("No user");
}

What’s wrong?
undefined means a variable has been declared but not assigned a value, while null is a value that represents "no value". Using them interchangeably causes bugs.

Fix:
Use strict equality checks when needed, and ensure you initialize variables appropriately:

if (user == null) { // checks for both null and undefined
console.log("No user");
}

II. Forgetting let, const, or var

The Error:

x = 10;

What’s wrong?
This creates a global variable unintentionally, which can lead to unexpected behavior or conflicts.

Fix: Always declare your variables properly:

let x = 10; // or const x = 10;

III. Incorrect Use of 'this'

The Error:

const user = {
name: "Jane",
greet: function () {
setTimeout(function () {
console.log(Hi, I'm ${this.name});
}, 1000);
}
};
user.greet(); // Outputs: "Hi, I'm undefined"

Why it happens:
In the setTimeout function, this doesn’t refer to user but to the global object.

Fix:
Use an arrow function to preserve this:

setTimeout(() => {
console.log(Hi, I'm ${this.name});
}, 1000);

IV. Misunderstanding Asynchronous Behavior

The Error:

let data = fetch("https://api.example.com/data");
console.log(data); // Promise { }

Why it happens:
fetch() returns a promise, and JavaScript doesn’t wait for it unless you tell it to.

Fix:
Use async/await:

async function getData() {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
}
getData();

V. Not Handling Errors in Promises

The Error:

fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data));

What’s missing?
There's no error handling. If something goes wrong, you won’t know.

Fix: Always handle rejections:

fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error fetching data:", error));

VI. Using = Instead of == or ===

The Error:

if (a = 5) {
// This will always be true!
}

Why it happens:
The single = is an assignment, not a comparison.

Fix:
Use === for strict comparison:

if (a === 5) {
// correct
}

VII. Modifying Objects or Arrays Directly

The Error:

const arr = [1, 2, 3];
const newArr = arr;
newArr.push(4);
console.log(arr); // [1, 2, 3, 4]

What’s wrong?
Both variables reference the same array in memory.

Fix:
Use spread syntax to copy:

const newArr = [...arr];

VIII. Looping with var Instead of let

The Error:

for (var i = 0; i < 5; i++) {
setTimeout(() => console.log(i), 1000);
}
// Logs: 5, 5, 5, 5, 5

Fix: let has block scope:

for (let i = 0; i < 5; i++) {
setTimeout(() => console.log(i), 1000);
}
// Logs: 0, 1, 2, 3, 4

IX. Not Using const for Constants

Using let for values that never change can lead to accidental reassignments.

Fix: Use const for values that don't change:

const PI = 3.14159;

X. DOM Not Ready Before Script Execution

The Error:

document.getElementById("btn").addEventListener("click", () => {});
// Error if the script runs before DOM is ready

Fix: Place your at the bottom of the HTML file or wrap it in a DOM-ready event:

document.addEventListener("DOMContentLoaded", () => {
document.getElementById("btn").addEventListener("click", () => {});
});


Conclusion:

JavaScript errors are often easy to make but just as easy to avoid once you understand the language’s quirks. By learning these common mistakes and practicing clean, intentional coding habits, you’ll be on your way to writing more robust and error-free JavaScript.