Write Clean JavaScript Code: Essential Tips
written by Idriss Douiri
4 min read
Ever stared at a screen filled with cryptic JavaScript code, tangled in loops and obscure variable names? Deciphering such code can be a frustrating nightmare, leading to errors and wasted time. But fear not! Clean code is here to the rescue.
Clean JavaScript code prioritizes readability, maintainability, and scalability. It’s code that not only works but also makes perfect sense – to you, your team, and even future developers who might inherit your project. In this article, we’ll delve into essential techniques and best practices to help you write clean JavaScript code that sings, making your development experience smoother and your code more robust.
Use descriptive naming
Your variables and functions should talk about your code without writing extra comments, and to ensure that, follow these steps:
- Don’t use single letters or generic names, as they provide little or no context about the variable’s purpose. Instead, use more descriptive and meaningful names, even if they are longer.
- Avoid abbreviations because they might confuse you or your team after revisiting your code a few days later unless it is universally understood (e.g., HTTP, API, CSS).
- Use one naming convention in all your projects: camelCase for variables and functions (e.g., userName), UPPERCASE for constants (e.g., PI), and PascalCase for classes (e.g., Player), and avoid using Hungarian notation (e.g., strName) as it adds unnecessary characters describing the type of the variable while you can hover on your variable and your IDE will tell you which type it is.
// bad naming
const x = 100;
const data = ["John", "Grace", "Jamir"];
// good naming
const totalItemsInStock = 100;
const userNames = ["John", "Grace", "Jamir"];
Avoid magic numbers
Magic numbers in programming are numeric values that lack explanation, which can lead to confusion and hard readability. You can avoid them by replacing the numbers with named constants that carry the meaning and maybe the why as well, this will make it easier for future developers to understand your code.
// with magic number
const totalPrice = price * 0.8;
// without magic number
const discount = 0.2;
const totalPrice = price * (1 - discount);
Good Formatting and structure
Your code structure and how you format it can make a huge difference and significantly enhance the readability of your code. To properly format your code, do the following:
- use consistent indentation (around 3 or 4 spaces) to visually distinguish each code block,
- keep your lines short (about 80 characters) to make your code visible on your screen without scrolling horizontally,
- separate each logic section with a blank line to facilitate the scanning through the code.
- Avoid deep nesting as it gets harder to follow by breaking down complex logic into smaller functions, or using an early-return statement.
- make your code breathe by adding spaces between symbols.
Instead of manually formatting your code and wasting your time, use a code formatter like Prettier to automatically format your code after saving
// harde to read
function add(x,y) {
if(!isNaN(x)&&!isNaN(y)) {
return +x+ +y;
}
}
// easier to read
function add(x, y) {
if (isNaN(x) && isNaN(y)) return;
return +x + +y;
}
DRY principle
Don’t Repeat Yourself (DRY) is a principle that consists of extracting any duplicate code to its reusable function, so you only have to change it from one place if needed.
Comments: Why, Not How
Comments are a great way to explain the reason behind complex code, maybe because that algorithm is more efficient in that case, or you tried other solutions but didn’t work.
Comments are used to explain the why, not the how. The code itself is very good at expressing what it’s doing.
Remove Redundancy
Clean up your code from any unnecessary extras that do nothing but add more characters. Such as unnecessary checks (e.g., isEven === true
).
// Bad
function isEvent(number) {
if (number % 2 === 0) {
return true;
} else {
return false;
}
}
// Better
function isEvent(number) {
return number % 2 === 0;
}
Bonus Tip: Modern JS
Use modern JavaScript to boost your code’s readability with its syntactical sugar. Some features that might help:
- short-circuiting evaluation (&&, ||) for navigating conditions easily.
- optional chaining (e.g., user?.address?.city) eliminiting undefined checks on objects.
- numeric separators (1_895_755 instead of 1895755) for improving the readability of large numbers.
Conclusion
By following these essential tips and best practices, you can confidently write clean and readable javascript code to make it easier for future developers.