Home > Article > Web Front-end > **Spread Syntax vs Rest Parameter: What\'s the Difference in ES2015?**
Spread Syntax and Rest Parameter: Unraveling Their Differences in ES2015
Navigating the nuances of spread syntax and rest parameter in ES2015 can be a mind-boggling endeavor. In this guide, we'll dissect their contrasting roles in JavaScript's ever-evolving landscape.
Understanding Spread Syntax: From One to Many
Spread syntax (denoted by '...') allows us to expand an iterable (e.g., an array) into its individual elements. It operates on a single variable, breaking it into smaller parts:
<code class="js">var abc = ['a', 'b', 'c']; var def = ['d', 'e', 'f']; var alpha = [ ...abc, ...def ]; console.log(alpha); // alpha will output ['a', 'b', 'c', 'd', 'e', 'f']</code>
By using spread syntax with '...' before 'abc' and 'def', we're effectively flattening these arrays into a single, merged array.
Unveiling the Rest Parameter: From Many to One
In contrast, the rest parameter (also preceded by '...') captures multiple elements from a function's argument list and combines them into a single array. This technique is commonly employed when we want to handle an unknown number of arguments:
<code class="js">function sum(...args) { var sum = 0; for (var i = 0; i < args.length; i++) { sum += args[i]; } return sum; } console.log(sum(1, 2, 3, 4, 5)); // sum will output 15</code>
Here, '...args' acts as a placeholder for all the arguments passed to the 'sum' function, which are then stored in the 'args' array.
Key Differences: Spread vs Rest
While both spread syntax and rest parameter utilize the '...' operator, they serve distinct purposes:
In essence, spread syntax helps you break down a variable into its parts, while the rest parameter consolidates multiple variables into a cohesive unit.
The above is the detailed content of **Spread Syntax vs Rest Parameter: What\'s the Difference in ES2015?**. For more information, please follow other related articles on the PHP Chinese website!