Quick tips for making your code readable and maintainable.
How many times have you opened an old project and found messy code that easily crashed when you added something new? We’ve all been there.
To reduce the amount of hard-to-read javascript, I provide the following example. These are all mistakes I’ve made in the past.
Use array destructuring for functions that have multiple return values
Suppose we have a function that returns multiple values. One possible implementation is to use array deconstruction, as follows:
const func = () = > {
const a = 1;
const b = 2;
const c = 3;
const d = 4;
return [a,b,c,d];
}
const [a,b,c,d] = func();
console.log(a,b,c,d); / / 1, 2, 3, 4
Copy the code
While the above approach works well, it does introduce some complexity.
When we call a function and assign values to a, B, C, or D, we need to pay attention to the order in which the data is returned. A small error here can be a debugging nightmare.
Furthermore, there is no way to specify exactly what values we want from the function, so what if we only need C and D?
Instead, we can use object deconstruction.
const func = () = > {
const a = 1;
const b = 2;
const c = 3;
const d = 4;
return {a,b,c,d};
}
const {c,d} = func();
Copy the code
Now we can easily choose the data we want from the function, which also provides future security for our code, allowing us to add additional return variables without breaking things.
Do not use object decomposition for function arguments
Suppose we have a function that takes an object as an argument and performs some operations on its properties. A naive approach might look something like this:
/ / do not recommend
function getDaysRemaining(subscription) {
const startDate = subscription.startDate;
const endDate = subscription.endDate;
return endDate - startDate;
}
Copy the code
The above method works as expected, but we create two unnecessary temporary references to startDate and endDate.
A better implementation is to use object deconstruction for the Subscription object to get startDate and endDate on a single line.
/ / recommend
function getDaysRemaining(subscription) {
const { startDate, endDate } = subscription;
return startDate - endDate;
}
Copy the code
We can go one step further and perform object destructor directly on the parameters.
/ / better
function getDaysRemaining({ startDate, endDate }) {
return startDate - endDate;
}
Copy the code
More elegant, isn’t it?
Copy an array without using the extension operator
Using a for loop to iterate over a number and copy its elements into a new array is tedious and rather ugly.
Extension operators can be used in a neat and straightforward way to achieve the same effect.
const stuff = [1.2.3];
/ / do not recommend
const stuffCopyBad = []
for(let i = 0; i < stuff.length; i++){
stuffCopyBad[i] = stuff[i];
}
/ / recommend
const stuffCopyGood = [...stuff];
Copy the code
The use of var
Using const guarantees that variables cannot be reassigned. This will reduce errors in our code and make it easier to understand.
/ / do not recommend
var x = "badX";
var y = "baxY";
/ / recommend
const x = "goodX";
const y = "goodX";
Copy the code
If you do need to reassign variables, always choose let over var.
This is because let is block-scoped, while VAR is function-scoped.
A block scope tells us that a variable can only be accessed inside the code block in which it is defined, and attempting to access a variable outside the block gives us a ReferenceError.
for(let i = 0; i < 10; i++){
//something
}
print(i) // ReferenceError: i is not defined
Copy the code
A function scope tells us that variables can only be accessed inside the function that defines them.
for(var i = 0; i < 10; i++){
//something
}
console.log(i) / / 10
Copy the code
Let and const are block-scoped.
Do not use template literals
Concatenating strings together manually is cumbersome and can cause confusion when typing. Here’s an example:
/ / do not recommend
function printStartAndEndDate({ startDate, endDate }) {
console.log('StartDate:' + startDate + ',EndDate:' + endDate)
}
Copy the code
Template literals give us a readable and concise syntax that supports string interpolation.
/ / recommend
function printStartAndEndDate({ startDate, endDate }) {
console.log(`StartDate: ${startDate}, EndDate: ${endDate}`)}Copy the code
Template text also provides an easy way to embed new lines. All you need to do is press Enter on your keyboard as usual.
// Two lines of print
function printStartAndEndDate({ startDate, endDate }) {
console.log(`StartDate: ${startDate}
EndDate: ${endDate}`)}Copy the code
Source:medium.com”, by Giuseppe Picciano, translated by Public account front-end Full Stack Developer