Like any kind of apps, JavaScript apps also have to be written well.
Otherwise, we run into all kinds of issues later on.
In this article, we’ll look at some best practices we should follow when writing JavaScript code.
Syntactic Sugar
Lots of recent changes in JavaScript are syntactic sugar for existing syntax.
We can make our lives easier with them.
There are several drop-in replacements that we can use with existing code.
let and const
We can use let
and const
to declare block-scoped variables.
They’re only available after they’re defined.
For example, we can write:
let x = 1;
const y = 2;
to make declare them.
Then we use them only after they’re declared.
const
variables can’t be reassigned to a new value, but we can change things inside it if it’s an object.
Limiting the Scope of the Function
We can limit the scope of the function with arrow functions.
For example, instead of writing:
function foo(){}
which can be called anywhere even before it’s defined.
We write:
const foo = () => {}
If we don’t need the function to bind to its own this
, then we definitely should use arrow functions.
They also can’t be called before they’re defined.
Class
Traditional constructor functions have been superseded by classes.
So instead of writing:
function Animal(name){
this.name = name;
}
Animal.prototype.speak = function (){
console.log(this.name);
}
We write:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name);
}
};
Everything is in one place and it resembles actual classes even though it’s just syntactic sugar.
Naming Variables
We should name variables in a way that we can understand.
For instance, instead of writing:
let d ;
let elapsed;
We write:
let daysSinceUpdate
They should also be easy to pronounce so we won’t have a hard time processing them.
So we can write something like:
let firstName, lastName
Writing Functions
We should make functions that do one thing.
So we should write functions like:
const add = (a, b) => a + b;
It only adds.
Use Long, Descriptive Names
The names we have above are descriptive.
They communicate their intent.
For example, instead of writing:
function inv(user) {
//...
}
We write:
function inviteUser(user) {
//...
}
Avoid Long Argument List
We should avoid long lists of arguments in our code.
If we need lots of arguments, we should put them in an object.
The fewer arguments we have, the easier it is for us to handle.
For instance, instead of writing:
function getRegisteredUsers(fields, include, fromDate, toDate) {
//...
}
We write:
function getRegisteredUsers({ fields, include, fromDate, toDate }) {
//...
}
We have one object parameter instead of multiple parameters.
This way, we still have names for them but we can retrieved them in any order.
Reduce Side Effects
We shouldn’t have unnecessary side effects in our code.
For instance, instead of writing:
function addItemToCart (item, quantity = 1) {
cart.set(item.id, quantity)
return cart
}
We write:
function addItemToCart(cart, item, quantity = 1) {
const cartCopy = { ...cart };
cartCopy.set(item.id, quantity)
return cartCopy;
}
Instead of accessing the cart
which is somewhere outside the function, we make a copy of it and then do the manipulate it the way we want and return the copy.
Organize Functions in a File According to the Step-down Rule
Higher level fuicntions should be on top and lower level functions should be below them.
This way, the order that they’re read is logical.
For instance, instead of writing:
function getFullName(user) {
return `${user.firstName} ${user.lastName}`
}
function renderEmail(user) {
// ...
const fullName = getFullName(user)
return `Dear ${fullName}, ...`
}
We write:
function renderEmail(user) {
// ...
const fullName = getFullName(user)
return `Dear ${fullName}, ...`
}
function getFullName(user) {
return `${user.firstName} ${user.lastName}`
}
getFullName
is a helper for renderEmail
, so it should below it.
Conclusion
We can use some syntactic sugar to make our lives easier.
Also, we should place our code more carefully to make working with it easier later on.