Rest Parameters Collect Variadic Arguments

A rest parameter gathers trailing arguments into a real array, replacing arguments; the spread call syntax and destructuring rest feed the same mechanism.

JavascriptData Integrity

Code

javascriptsnippet
16 lines
// rest parameter gathers trailing arguments into a real array, replacing arguments
function stats(label, ...values) {
  const sum = values.reduce((total, n) => total + n, 0);
  return `${label}: n=${values.length} sum=${sum}`;
}

console.log(stats("scores", 8, 9, 7));
console.log(stats("empty"));
console.log(stats("spread", ...[4, 5, 6]));

// rest 必须是最后一个参数;解构里它收集剩余元素
const [first, ...others] = [1, 2, 3, 4];
console.log("first:", first, "rest:", others);

const { name, ...meta } = { name: "build", time: 12, tries: 2 };
console.log("name:", name, "meta keys:", Object.keys(meta).join(","));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

scores: n=3 sum=24
empty: n=0 sum=0
spread: n=3 sum=15
first: 1 rest: [ 2, 3, 4 ]
name: build meta keys: time,tries

How the snippet works

The code’s whole job belongs to the function stats.

Caveats

  • Everything it calls is documented as part of the language core.

Using it

The main signature reads function stats(label, ...values)

The demo output is labeled (first:, name:), so every printed line maps back to its originating operation.

Key statements

const sum = values.reduce((total, n) => total + n, 0);
return `${label}: n=${values.length} sum=${sum}`;

Interactive Tools for This Topic

FAQ

Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. The file defines `stats` at load time.