• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Common Errors in JavaScript (And How to Avoid Them)

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
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("

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

);
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("

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

);
const data = await response.json();
console.log(data);
}
getData();

V. Not Handling Errors in Promises

The Error:

fetch("

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

)
.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("

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

)
.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:</p> <p>document.addEventListener(&quot;DOMContentLoaded&quot;, () =&gt; {<br> document.getElementById(&quot;btn&quot;).addEventListener(&quot;click&quot;, () =&gt; {});<br> });</p> <hr> <p>Conclusion:</p> <p>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.</p> <hr>


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу