liveBook · Manning

Rest operator

As explained in Secrets of the JavaScript Ninja, Second Edition

A function parameter syntax that collects remaining supplied arguments into a single array-like value.

A rest parameter collects the remaining arguments passed to a function into a new array. Write it with `...` before the parameter name, and place it last in the parameter list. section 3.4.1 section 3.5

Collecting the remaining numbers

In `multiMax(3, 1, 2, 3)`, `first` receives `3` and `remainingNumbers` receives `[1, 2, 3]`. The function sorts that array in descending order, then multiplies the first value by the largest. Sorting works here, though the example notes it is not the most efficient way to find the largest number. section 3.4.1

Listing 3.7. Using rest parameters
  function multiMax(first, ...remainingNumbers){                  #A
    var sorted = remainingNumbers.sort(function(a, b){
       return b – a;                                              #B
    });
    return first * sorted[0];
  }
  assert(multiMax(3, 1, 2, 3) == 9,                               #C
        "3*3=9 (First arg, by largest.)"); 

See the complete `multiMax` function and its call. section 3.4.1

Only the final function parameter can be a rest parameter; placing another parameter after it causes a `SyntaxError`. Rest parameters provide a way to access excess arguments without using the legacy `arguments` object. section 3.4.1 section 4.1.1

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains the syntax, array collection, and final-parameter restriction, and demonstrates sorting without detailing browser compatibility.
Examples
Demonstrates `multiMax(3, 1, 2, 3)`, sorting the remaining values, and multiplying the first by the largest.
What it assumes
Assumes familiarity with JavaScript functions and the distinction between parameters in definitions and arguments passed at invocation.
What you can do after
Apply `...name` to collect remaining arguments into an array and process them inside a function.
How it connects
Connects rest parameters to function arguments, parameter assignment, and the legacy `arguments` object.

Also explained in

Compare how 3 books explain rest operator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.