Search⌘ K
AI Features

Spread Operator and Rest Parameters

Explore how to use the spread operator to expand arrays and objects and simplify function calls. Understand how rest parameters gather remaining function arguments into an array, enhancing code flexibility and readability.

The Spread operator #

According to MDN:

Spread syntax allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

 

Combine arrays #

Javascript (babel-node)
const veggie = ["tomato","cucumber","beans"];
const meat = ["pork","beef","chicken"];
const menu = [...veggie, "pasta", ...meat];
console.log(menu);
// Array [ "tomato", "cucumber", "beans", "pasta", "pork", "beef", "chicken" ]

The ... is the spread syntax, and it allowed us to grab all the individual ...