Wave Goodbye to 7 Poor JavaScript Habits
Written on
Chapter 1: Introduction
Throughout my career, I've encountered and even adopted numerous bad coding practices. Reflecting on these habits now, I realize how detrimental they can be to code quality and maintainability.
Section 1.1: The Perils of One-Line Code
Writing code in a single line might seem impressive, but it often sacrifices readability. For instance, I once cleared all cookies using a single line:
document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, =;expires=${new Date(0).toUTCString()};path=/));
However, this approach is nearly impossible to read. A clearer alternative might look like this:
const cookies = document.cookie.split(';');
cookies.forEach(cookie => {
cookie = cookie.replace(/^ +/, '');
cookie = cookie.replace(/=.*/, =;expires=${new Date(0).toUTCString()};path=/);
document.cookie = cookie;
});
Section 1.2: Error Handling in JavaScript
Do you often overlook error handling? Many developers focus solely on successful outcomes, neglecting failed requests. For instance, I would log errors like this:
try {
fetch(url, {
method: 'post',
...
});
} catch (err) {
console.log(err);
}
Instead, we should consider informing users of any issues:
try {
fetch(url, {
method: 'post',
...
});
} catch (err) {
Toast(err.message);
}
Section 1.3: The Dangers of Magic Numbers
Magic numbers can be confusing. Without context, they lack meaning. For example:
if (status === 1 || status === 2) {
// ...
} else if (status === 3) {
// ...
}
Defining constants improves clarity:
const STATUS = {
adultRealName: 1,
minorRealName: 2,
notRealName: 3,
};
if ([STATUS.adultRealName, STATUS.minorRealName].includes(status)) {
// ...
} else if (status === STATUS.notRealName) {
// ...
}
Section 1.4: Avoiding Callback Hell
In 2023, we should move beyond excessive callback nesting, which can make code hard to follow. Instead, using await enhances readability:
const a = await fetch('/a');
const b = await fetch('/b', { a });
const c = await fetch('/c', { b });
console.log(c);
Section 1.5: The Problem with Too Many Parameters
Functions that require numerous parameters can be difficult to use. Consider this example:
const getUser = (name, weight, mobile, gender, address, hobby, ...) => {
// ...
};
Redesigning the function to accept an object simplifies usage:
const getUser = (options) => {
const { name, weight, mobile, gender, address, hobby, ... } = options;
// ...
};
getUser({
name: 'fatfish',
weight: 100,
mobile: 183,
});
Section 1.6: Converting Strings to Numbers
While it might seem convenient to convert strings to numbers using the + operator:
const str = '123456';
const num = +str;
Using Number or parseInt is clearer and more semantic:
const str = '123456';
const num1 = Number(str);
const num2 = parseInt(str);
console.log({ num1, num2 });
Section 1.7: Modifying node_modules
Altering the code in node_modules directly is a risky practice. It can lead to issues when handing off projects, as changes may be lost:
// .gitignore
node_modules/
dist/
Ending
If you have encountered other bad JavaScript practices, please share your insights in the comments. I look forward to learning from your experiences!
In Plain English 🚀
Thank you for being part of the In Plain English community! Before you leave, consider following us for more content.
The first video, "Goodbye JavaScript (for now)," provides insights into common pitfalls and how to improve your coding practices.
The second video, "Goodbye JavaScript," offers a deeper dive into effective JavaScript strategies for cleaner code.