The spread operator and rest parameter are two other powerful features introduced in ECMAScript 2015 and they allow us to write more concise and flexible code like most of the other ES6 features do. The several different ways you can use spread and rest syntax will be covered in this article.


Spread Operator

The spread operator allows us to expand the collected elements of an iterable data type like strings, arrays, or objects into individual elements in places. It helps to create a list of elements from a list by spreading out the values of an iterable where zero or more arguments (function calls) or elements (array literals) or key-value pairs (object literals) are expected.

1. In Function Calls:

The spread operator can be used to take elements of an array and pass them as a list of arguments into a function. Let’s take a look at how it works:

The elements of an array are passed to a function as arguments

The function printColors takes in three parameters and we want to pass three arguments stored in colors array. When we call the function, the spread operator unpacks the passed array of arguments, ‘red’‘blue’, and ‘yellow’.

#es6 #javascript #rest-parameter #programming #spread-operator

JavaScript: Spread Operator and Rest Parameter (ES6)
1.65 GEEK