Home > Web Front-end > JS Tutorial > ## What\'s the Difference Between Spread Syntax and Rest Parameters in ES6?

## What\'s the Difference Between Spread Syntax and Rest Parameters in ES6?

Barbara Streisand
Release: 2024-10-24 17:23:02
Original
1062 people have browsed it

## What's the Difference Between Spread Syntax and Rest Parameters in ES6?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template