DEV Community

Cover image for Enough JavaScript to get you Started : #17 rest,spread and destructuring
Adarsh Pandya
Adarsh Pandya

Posted on

Enough JavaScript to get you Started : #17 rest,spread and destructuring

rest and spread operator (...)

πŸ‘‰ rest and spread operators came out with release of ECMA6


πŸ‘‰... can be used as rest as well as spread operator

rest

πŸ‘‰ collects all remaining params into a single array

πŸ‘‰ Problem statement : write a function which can perform sum of N numbers

πŸ‘‰Code

const sum = (n1,n2,n3) => {
       return n1+n2+n3;
}
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ this solution works for only 3 numbers but as per the definition we've to add N numbers

πŸ‘‰ now the problem is we don't know how many params are going to passed maybe 3 maybe 5 maybe 100?

πŸ‘‰ we can't write 100 function for 100 numbers

πŸ‘‰ Solution : use rest operator

πŸ‘‰ rest operator (...) collects all the actual values passed and then combines them into one array , so we can pass n number of params without having to write separate functions for each of problems

πŸ‘‰ Example

const sumOfN = (...elements) => {
     let total = 0;
     // remember rest passes array as arguement
     // we'll loop through each element and add them into total.
     for(i=0;i<elements.length;i++)
     {
             // += is short hand for 'total = total + elements[i]`
             total+=elements[i]; // will add items from array one by one
     }
     return total;
}

// let's check
sumOfN(1); // βœ” returns 1
sumOfN(1,2); // βœ” returns 3
sumOfN(1,2,3); // βœ” returns 6
sumOfN(1,2,3,4); // βœ” returns 10
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ according to ECMA standards the param which will use rest operator need to be last in parameters

πŸ‘‰ Example : sumOfN(someOtherVar,...elements)


Spread operator

πŸ‘‰ Spread operator have similar (...) expression as rest operator but it works in different context


πŸ‘‰Spread operators allows us to expand elements without having to write loops explicitly

Let's understand it through example
πŸ‘‰ Problem statement : create a program which can merge two arrays

πŸ‘‰ The old way :

let arr1=[1,2,3];
let arr2 = [4,5,6];
let mergedArray = [];
for(let item of arr1)
{      
       // push method is used to push elements into array at last index
       mergedArray.push(item);
}
for(let item of arr2)
{      
       mergedArray.push(item);
}

console.log(mergedArray);
// will print [1,2,3,4,5,6]
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ The new way with spread operator :

let arr1 = [1,2,3];
let arr2 = [4,5,6];

// '...arr1' will unpack 1,2,3 into mergedArray
// '...arr2' will unpack 4,5,6 into mergedArray
let mergedArray = [...arr1,...arr2];

console.log(mergedArray);
// will print [1,2,3,4,5,6]
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Spread makes it easy to work with day to day array operations


Destructuring

πŸ‘‰ Descructuring in JavaScript simply refers to popping out the desired values from Objects and Arrays

πŸ‘‰ Example : The old way

const πŸ• = {
       name : "sharron",
       color : "black",
       age : 9
}

// old way to access values
const name = πŸ•.name;
const color = πŸ•.color;
const age = πŸ•.age;

Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Example : The new way

const πŸ• = {
       name : "sharron",
       color : "black",
       age : 9
}

// using destructuring to extract values
const {name,color,age} = πŸ•;

console.log(name); // sharron
console.log(color);  // black
console.log(age);    // age

const heros = ['iron man', 'super man', 'spider man'];

const [hero1, hero2, hero3] = heros;
console.log(hero1); // "iron man"
console.log(hero2); // "super man"
console.log(hero3); // "spider man"
Enter fullscreen mode Exit fullscreen mode

Let me know in comment section if you have any doubt or feedback. it's always worth to give time to the thriving developer community :)

Keep Coding ❀

Hey , Let' ConnectπŸ‘‹

Twitter /
Github

Top comments (5)

Collapse
 
_genjudev profile image
Larson • Edited

You could also write your sum function like that:

const sum = (...el) => el.reduce((a, c) => a + c);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
whoadarshpandya profile image
Adarsh Pandya

Nice idea ! reduce, map and bind are being written in upcoming article :)

Collapse
 
waynear19 profile image
Wayne Richard

Nice job on this entire series.

Collapse
 
hamzamateen profile image
HamzaMateen

Great, concise!

Collapse
 
whoadarshpandya profile image
Adarsh Pandya

Respecting everyone's time is great thing to do πŸ˜‰