DEV Community 👩‍💻👨‍💻

Cover image for The ...spread operator and the rest parameters
Avinesh
Avinesh

Posted on

The ...spread operator and the rest parameters

Spread operator

As the name suggests the spread operator spreads or expands an iterable such as an array or string into individual elements.

Few use cases

  • Adding elements of one array to new array.
  • Passing an array as argument to a function.
  • Array concatenation.
  • Array copy.

Adding elements of one array to new array

var arr1 = [3,4,5];
var arr2 = [1,2,...arr1,6,7];
console.log(arr2); // output -> [1,2,3,4,5,6,7]
Enter fullscreen mode Exit fullscreen mode

Passing an array as argument to a function

function addAll(a,b,c,d){
console.log(a+b+c+d); // output -> 10
}
var arr = [1,2,3,4];
addAll(...arr);
Enter fullscreen mode Exit fullscreen mode

Array concatenation

var arr1 = [1,2,3];
var arr2 = [4,5,6];
arr1 = [...arr1,...arr2];
console.log(arr1); // output -> [1,2,3,4,5,6]
Enter fullscreen mode Exit fullscreen mode

Array copy

var arr1 = [1,2,3,4];
var arr2 = [...arr1];
console.log(arr2); // output -> [1,2,3,4]
Enter fullscreen mode Exit fullscreen mode

Rest parameters

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

function findProduct(...args){
var result = 1;
args.map((arg)=>{
result = result * arg;
});
return result;
}

console.log(findProduct(2,4,6)); // output -> 48
Enter fullscreen mode Exit fullscreen mode

Points to take away

  • Spread operator unpacks an iterable into individual elements.
  • Rest parameter collects multiple individual elements and packs them into an array.

Top comments (0)

⬇️ The only reason people scroll to the bottom...

 

is because they want to read more. Sign up for an account to bookmark, comment, and react to articles that interest you.