Spread Syntax vs. Rest Parameter in ES2015 / ES6
JavaScript ES2015 introduced two important features that can be easily confused: spread syntax and rest parameter. Both of them utilize the three dots notation (...). However, they serve distinct purposes.
Spread Syntax
Spread syntax is used to expand an iterable into its individual elements. This can be applied to arrays, strings, or objects. For instance, consider the following code:
<code class="javascript">const abc = ['a', 'b', 'c']; const def = ['d', 'e', 'f']; const alpha = [...abc, ...def];</code>
In this example, the spread syntax is used to expand the abc and def arrays into the new alpha array. As a result, alpha will contain all the elements from both abc and def.
Rest Parameter
In contrast, the rest parameter is used in function definitions to collect the remaining arguments passed to the function. It is denoted by three dots followed by a variable name. For example:
<code class="javascript">function sum(...rest) { let result = 0; rest.forEach(num => result += num); return result; }</code>
In the sum function, the rest parameter ...rest gathers all the arguments passed to the function and stores them in the rest array. Then, it iterates through rest and accumulates the sum of its elements.
The above is the detailed content of ## What\'s the Difference Between Spread Syntax and Rest Parameters in ES6?. For more information, please follow other related articles on the PHP Chinese website!