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

Discussion (5)

Collapse
larsonnn profile image
Lars Feldeisen • Edited on

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 Author

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 Author

Respecting everyone's time is great thing to do 😉