How many times have you opened an old project to find confusing code that easily breaks when you add something new to it? We’ve all been there.

In a hope to lessen the amount of unreadable javascript in the world, I present to you the following examples. All of which I have been guilty of in the past.

Using Array Destructuring For Functions With Multiple Return Values

Suppose we have a function that returns multiple values. One possible implementation is to use array destructuring 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); // Outputs: 1,2,3,4

While the above approach works fine, it does introduce some complexities.

When we call the function and assign the values to a,b,c,d we need to be attentive to the order that the data is returned in. A small mistake here may become a nightmare to debug down the road.

Additionally, it is not possible to specify exactly which values we would like from the function. What if we only needed c and d ?

Instead, we can use** object destructuring.**

const func = () => {
  const a = 1;
  const b = 2;
  const c = 3;
  const d = 4;
  return {a,b,c,d};
}
const {c,d} = func();

Now we can easily select the data we require from the function.

This also future-proofs our code by allowing us to add additional return-variables over time without breaking things.

#javascript #javascript tips #web development

Stop Making These 5 Javascript Style Mistakes
57.30 GEEK