Spread & Rest operator

Spread operator

With the new ES2015 standard came a new operator “…” which can split an array into a list and vice versa to group a list into an array. Depending on the function it performs, this parameter has the name “spread” or “rest”. If the operator is in front of the iterable object and “spreads” the iterator (eg array) into individual values ​​creating a list, then it is called “spread”.

Transform a string to a list of arguments

This operator is a replacement for a frequently used problem when it is necessary to cast a string into a list of arguments. And the best example is “expanding” a string in a function’s argument list. This operator is used when calling the function:

Declarations of an array containing another array

Used within an array declaration that contains another array:

Cloning an object

With the new standard, it is allowed to use the spread operator within the object literal. This convenience allows us to easily clone objects using the spread operator, without using the Object.assign() method:

Merging two objects

Using the spread operator makes it easy to join two objects without duplicating properties:

Rest operator

Unlimited number of arguments as a string

The Rest syntax allows us to represent an unlimited number of arguments as an array. This operator is used when defining a function by grouping the remaining arguments into an array:

The collected string can be destroyed into individual values if necessary.

List to array transformation

This operator replaces the overcomplicated solution used to cast a list to an array :

New way with rest operator:

BONUS: Spread/rest operator associativity

Each JavaScript operator has its own “importance” which is directly related to associability and how to determine which operation takes precedence in the absence of parentheses. The Sread/Rest operator belongs to the “weaker” operators (ie, the only weaker , “comma” operator). See the operator importance table in the article “JavaScript operator”.

Example

In the JavaScript world, we can come across the following expression:

The essential part of this whole expression is actually this hard-to-understand part:

es6

In order to understand the expression, we need to know which operator is more important, i.e. preference when executing an expression. The following list shows the operators in this expression by “meaning”:

  1. !! (negation operator)
  2. … ? … : … (ternary operator)
  3. …(spread operator)

The preceding list determines the flow of the expression: first, with a double negation, the “data” variable is converted to a logical value (read more about this in the article “JS snippets (tips & tricks)”). If we get a TRUE logical value, then the ternary operator enters the scene, which takes the “data” object and then “spreads” it with the spread operator, for the FALSE value, the ternary operator returns the literal object and spreads it with the spread operator.