Write a much cleaner and more readable code with these few js tips & tricks.
Array Destructuring For Functions
In this first type, we will see how to destructure an array for a function with multiple return values.
The regular way:
const func = () => {
const clinton = 1;
const trump = 2;
const obama = 3;
const biden = 4;
return [clinton, trump, obama, biden];
}
const [clinton, trump, obama, biden] = func();
console.log(clinton, trump, obama, biden); // Outputs: 1,2,3,4
Instead, we can use object destructuring:
const func = () => {
const clinton = 1;
const trump = 2;
const obama = 3;
const biden = 4;
return { clinton, trump, obama, biden};
}
const { obama, biden } = func();
With this approach, it’s easier to select what we require from the function.
Object Destructuring For Function
The regular way:
function getDaysRemaining(subscription) {
const startDate = subscription.startDate;
const endDate = subscription.endDate;
return endDate - startDate;
}
A slightly better way:
function getDaysRemaining(subscription) {
const { startDate, endDate } = subscription;
return startDate - endDate;
}
Even better :)
function getDaysRemaining({ startDate, endDate }) {
return startDate - endDate;
}
With this, we have a smaller and cleaner looking code.
Copying Arrays
Normally we use for-loops to iterate over elements and copy it into a new array like so:
const oldArray = [1,2,3];
const newArray = []
for(let i = 0; i < oldArray.length; i++){
newArray[i] = oldArray[i];
}
Instead, a spread operator can be used to achieve a similar result like so:
const oldArray = [1,2,3];
const newArray = [...oldArray];
Template literals
Concatenation strings become a little complicated as the strings/variables grows.
The regular way:
function getSeason({ month, season }) {
console.log("It's " + season + ' in the month of ' + month)
}
Now let’s see using template literals.
function getSeason({ month, season }) {
console.log(`It's ${season} in the month of ${month}`)
}
As you can see comparing the above functions, it’s easier to read the return statement of the second function.
Finally
And finally using const
instead of var
. Using const
guarantees a variable cannot be reassigned. This reduces bugs in our code and makes it easier to debug.
Hope you found this article useful. If so hit 👍🏻 and spread the word by sharing!