Home > Web Front-end > JS Tutorial > body text

Spread Syntax vs. Rest Parameter: What\'s the Difference?

DDD
Release: 2024-10-25 07:35:02
Original
733 people have browsed it

Spread Syntax vs. Rest Parameter: What's the Difference?

Spread Syntax vs Rest Parameter: Understanding the Difference

In ES2015, two new features, spread syntax and rest parameters, provide powerful ways to manipulate arrays and objects. While both may seem similar, they serve distinct purposes and each has its own unique functionality.

Spread Syntax

Spread syntax (represented by three dots "...") allows you to spread or expand an iterable (such as an array or object) into individual elements within another iterable. This feature enables you to conveniently merge or combine multiple arrays or objects into a new one.

For example, let's consider the following code:

<code class="js">var abc = ['a', 'b', 'c'];
var def = ['d', 'e', 'f'];
var alpha = [ ...abc, ...def ];
console.log(alpha); // alpha == ['a', 'b', 'c', 'd', 'e', 'f'];</code>
Copy after login

In this snippet, the ...abc and ...def spread syntax expand the abc and def arrays into individual elements, creating a new alpha array containing all the elements from both arrays.

Rest Parameter

On the other hand, a rest parameter (denoted by three dots "...", preceded by an identifier) collects any remaining arguments passed to a function into a single array. The rest parameter must be the last parameter in the function's parameter list.

An example of a rest parameter in action is as follows:

<code class="js">function sumAll(...numbers) {
  let total = 0;
  for (let num of numbers) {
    total += num;
  }
  return total;
}

let result = sumAll(1, 2, 3, 4, 5);
console.log(result); // result == 15</code>
Copy after login

In this code, the ...numbers rest parameter collects the remaining arguments passed to the sumAll function (in this case, 1, 2, 3, 4, and 5) and creates a single numbers array.

The above is the detailed content of Spread Syntax vs. Rest Parameter: What\'s the Difference?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!