developer.mozilla.org Open in urlscan Pro
2600:9000:225e:da00:2:eb5:8c00:93a1  Public Scan

Submitted URL: https://mdn.io/rest_parameters
Effective URL: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters
Submission: On December 29 via api from US — Scanned from DE

Form analysis 1 forms found in the DOM

/en-US/search

<form action="/en-US/search" role="search" aria-haspopup="listbox" aria-owns="top-nav-search-menu" aria-expanded="false" class="search-form search-widget" id="top-nav-search-form"><label id="top-nav-search-label" for="top-nav-search-input"
    class="visually-hidden">Search MDN</label><input id="top-nav-search-input" aria-autocomplete="list" aria-controls="top-nav-search-menu" aria-labelledby="top-nav-search-label" autocomplete="off" type="search" class="search-input-field" name="q"
    placeholder="   " required="" value=""><button type="button" class="button action has-icon clear-search-button"><span class="button-wrap"><span class="icon icon-cancel "></span><span class="visually-hidden">Clear search
        input</span></span></button><button type="submit" class="button action has-icon search-button"><span class="button-wrap"><span class="icon icon-search "></span><span class="visually-hidden">Search</span></span></button>
  <div id="top-nav-search-menu" role="listbox" aria-labelledby="top-nav-search-label"></div>
</form>

Text Content

 * Skip to main content
 * Skip to search
 * Skip to select language

MDN Plus now available in your country! Support MDN and make it your own. Learn
more ✨


MDN Web DocsOpen main menu
 * ReferencesReferences
   * Overview / Web Technology
     
     Web technology reference for developers
   
   * HTML
     
     Structure of content on the web
   
   * CSS
     
     Code used to describe document style
   
   * JavaScript
     
     General-purpose scripting language
   
   * HTTP
     
     Protocol for transmitting web resources
   
   * Web APIs
     
     Interfaces for building web applications
   
   * Web Extensions
     
     Developing extensions for web browsers
   
   * Web Technology
     
     Web technology reference for developers
 * GuidesGuides
   * Overview / MDN Learning Area
     
     Learn web development
   
   * MDN Learning Area
     
     Learn web development
   
   * HTML
     
     Learn to structure web content with HTML
   
   * CSS
     
     Learn to style content using CSS
   
   * JavaScript
     
     Learn to run scripts in the browser
   
   * Accessibility
     
     Learn to make the web accessible to all
 * MDN PlusMDN Plus
   * Overview
     
     A customized MDN experience
   
   * 
     New feature
     Updates
     
     All browser compatibility updates at a glance
   
   * Documentation
     
     Learn how to use MDN Plus
   
   * FAQ
     
     Frequently asked questions about MDN Plus

Search MDNClear search inputSearch

Theme
 * Already a subscriber?
 * Get MDN Plus

 1. References
 2. JavaScript
 3. JavaScript
 4. Functions
 5. Rest parameters

Article Actions
 * English (US)


IN THIS ARTICLE

 * Try it
 * Syntax
 * Description
 * Examples
 * Specifications
 * Browser compatibility
 * See also

RELATED TOPICS

 1.  JavaScript
 2.  Tutorials:
 3.  Complete beginners
      1. JavaScript basics
      2. JavaScript first steps
      3. JavaScript building blocks
      4. Introducing JavaScript objects

 4.  JavaScript Guide
      1.  Introduction
      2.  Grammar and types
      3.  Control flow and error handling
      4.  Loops and iteration
      5.  Functions
      6.  Expressions and operators
      7.  Numbers and dates
      8.  Text formatting
      9.  Regular expressions
      10. Indexed collections
      11. Keyed collections
      12. Working with objects
      13. Using classes
      14. Using promises
      15. Iterators and generators
      16. Meta programming
      17. JavaScript modules

 5.  Intermediate
      1. Client-side JavaScript frameworks
      2. Client-side web APIs
      3. Language overview
      4. JavaScript data structures
      5. Equality comparisons and sameness
      6. Enumerability and ownership of properties
      7. Closures

 6.  Advanced
      1. Inheritance and the prototype chain
      2. JavaScript typed arrays
      3. Memory Management
      4. Concurrency model and Event Loop

 7.  References:
 8.  Built-in objects
      1.  Overview
      2.  AggregateError
      3.  Array
      4.  ArrayBuffer
      5.  AsyncFunction
      6.  AsyncGenerator
      7.  AsyncGeneratorFunction
      8.  Atomics
      9.  BigInt
      10. BigInt64Array
      11. BigUint64Array
      12. Boolean
      13. DataView
      14. Date
      15. decodeURI()
      16. decodeURIComponent()
      17. encodeURI()
      18. encodeURIComponent()
      19. Error
      20. Deprecated escape()
      21. eval()
      22. EvalError
      23. FinalizationRegistry
      24. Float32Array
      25. Float64Array
      26. Function
      27. Generator
      28. GeneratorFunction
      29. globalThis
      30. Infinity
      31. Int16Array
      32. Int32Array
      33. Int8Array
      34. Non-standard InternalError
      35. Intl
      36. isFinite()
      37. isNaN()
      38. JSON
      39. Map
      40. Math
      41. NaN
      42. Number
      43. Object
      44. parseFloat()
      45. parseInt()
      46. Promise
      47. Proxy
      48. RangeError
      49. ReferenceError
      50. Reflect
      51. RegExp
      52. Set
      53. SharedArrayBuffer
      54. String
      55. Symbol
      56. SyntaxError
      57. TypedArray
      58. TypeError
      59. Uint16Array
      60. Uint32Array
      61. Uint8Array
      62. Uint8ClampedArray
      63. undefined
      64. Deprecated unescape()
      65. URIError
      66. WeakMap
      67. WeakRef
      68. WeakSet

 9.  Expressions & operators
      1.  Overview
      2.  Addition (+)
      3.  Addition assignment (+=)
      4.  Assignment (=)
      5.  async function expression
      6.  async function* expression
      7.  await
      8.  Bitwise AND (&)
      9.  Bitwise AND assignment (&=)
      10. Bitwise NOT (~)
      11. Bitwise OR (|)
      12. Bitwise OR assignment (|=)
      13. Bitwise XOR (^)
      14. Bitwise XOR assignment (^=)
      15. class expression
      16. Comma operator (,)
      17. Conditional (ternary) operator
      18. Decrement (--)
      19. delete operator
      20. Destructuring assignment
      21. Division (/)
      22. Division assignment (/=)
      23. Equality (==)
      24. Exponentiation (**)
      25. Exponentiation assignment (**=)
      26. Function expression
      27. function* expression
      28. Greater than (>)
      29. Greater than or equal (>=)
      30. Grouping operator ( )
      31. import.meta
      32. import()
      33. in operator
      34. Increment (++)
      35. Inequality (!=)
      36. instanceof
      37. Left shift (<<)
      38. Left shift assignment (<<=)
      39. Less than (<)
      40. Less than or equal (<=)
      41. Logical AND (&&)
      42. Logical AND assignment (&&=)
      43. Logical NOT (!)
      44. Logical OR (||)
      45. Logical OR assignment (||=)
      46. Multiplication (*)
      47. Multiplication assignment (*=)
      48. new operator
      49. new.target
      50. null
      51. Nullish coalescing assignment (??=)
      52. Nullish coalescing operator (??)
      53. Object initializer
      54. Operator precedence
      55. Optional chaining (?.)
      56. Property accessors
      57. Remainder (%)
      58. Remainder assignment (%=)
      59. Right shift (>>)
      60. Right shift assignment (>>=)
      61. Spread syntax (...)
      62. Strict equality (===)
      63. Strict inequality (!==)
      64. Subtraction (-)
      65. Subtraction assignment (-=)
      66. super
      67. this
      68. typeof
      69. Unary negation (-)
      70. Unary plus (+)
      71. Unsigned right shift (>>>)
      72. Unsigned right shift assignment (>>>=)
      73. void operator
      74. yield
      75. yield*

 10. Statements & declarations
      1.  Overview
      2.  async function
      3.  async function*
      4.  block
      5.  break
      6.  class
      7.  const
      8.  continue
      9.  debugger
      10. do...while
      11. empty
      12. export
      13. for
      14. for await...of
      15. for...in
      16. for...of
      17. function declaration
      18. function*
      19. if...else
      20. import
      21. label
      22. let
      23. return
      24. switch
      25. throw
      26. try...catch
      27. var
      28. while
      29. Deprecated with

 11. Functions
      1. Overview
      2. Arrow function expressions
      3. Default parameters
      4. getter
      5. Method definitions
      6. Rest parameters
      7. setter
      8. The arguments object

 12. Classes
      1. Overview
      2. constructor
      3. extends
      4. Private class features
      5. Public class fields
      6. static
      7. Static initialization blocks

 13. Errors
      1.  Overview
      2.  Error: Permission denied to access property "x"
      3.  InternalError: too much recursion
      4.  RangeError: argument is not a valid code point
      5.  RangeError: BigInt division by zero
      6.  RangeError: BigInt negative exponent
      7.  RangeError: invalid array length
      8.  RangeError: invalid date
      9.  RangeError: precision is out of range
      10. RangeError: radix must be an integer
      11. RangeError: repeat count must be less than infinity
      12. RangeError: repeat count must be non-negative
      13. RangeError: x can't be converted to BigInt because it isn't an integer
      14. ReferenceError: "x" is not defined
      15. ReferenceError: assignment to undeclared variable "x"
      16. ReferenceError: can't access lexical declaration 'X' before
          initialization
      17. ReferenceError: deprecated caller or arguments usage
      18. ReferenceError: reference to undefined property "x"
      19. SyntaxError: "0"-prefixed octal literals and octal escape seq. are
          deprecated
      20. SyntaxError: "use strict" not allowed in function with non-simple
          parameters
      21. SyntaxError: "x" is a reserved identifier
      22. SyntaxError: a declaration in the head of a for-of loop can't have an
          initializer
      23. SyntaxError: applying the 'delete' operator to an unqualified name is
          deprecated
      24. SyntaxError: cannot use `??` unparenthesized within `||` and `&&`
          expressions
      25. SyntaxError: for-in loop head declarations may not have initializers
      26. SyntaxError: function statement requires a name
      27. SyntaxError: identifier starts immediately after numeric literal
      28. SyntaxError: illegal character
      29. SyntaxError: invalid assignment left-hand side
      30. SyntaxError: invalid BigInt syntax
      31. SyntaxError: invalid regular expression flag "x"
      32. SyntaxError: JSON.parse: bad parsing
      33. SyntaxError: Malformed formal parameter
      34. SyntaxError: missing ; before statement
      35. SyntaxError: missing : after property id
      36. SyntaxError: missing ) after argument list
      37. SyntaxError: missing ) after condition
      38. SyntaxError: missing ] after element list
      39. SyntaxError: missing } after function body
      40. SyntaxError: missing } after property list
      41. SyntaxError: missing = in const declaration
      42. SyntaxError: missing formal parameter
      43. SyntaxError: missing name after . operator
      44. SyntaxError: missing variable name
      45. SyntaxError: redeclaration of formal parameter "x"
      46. SyntaxError: return not in function
      47. SyntaxError: test for equality (==) mistyped as assignment (=)?
      48. SyntaxError: Unexpected '#' used outside of class body
      49. SyntaxError: Unexpected token
      50. SyntaxError: unparenthesized unary expression can't appear on the
          left-hand side of '**'
      51. SyntaxError: unterminated string literal
      52. SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated.
          Use //# instead
      53. TypeError: 'x' is not iterable
      54. TypeError: "x" has no properties
      55. TypeError: "x" is (not) "y"
      56. TypeError: "x" is not a constructor
      57. TypeError: "x" is not a function
      58. TypeError: "x" is not a non-null object
      59. TypeError: "x" is read-only
      60. TypeError: can't access dead object
      61. TypeError: can't assign to property "x" on "y": not an object
      62. TypeError: can't convert BigInt to number
      63. TypeError: can't convert x to BigInt
      64. TypeError: can't define property "x": "obj" is not extensible
      65. TypeError: can't delete non-configurable array element
      66. TypeError: can't redefine non-configurable property "x"
      67. TypeError: cannot use 'in' operator to search for 'x' in 'y'
      68. TypeError: cyclic object value
      69. TypeError: invalid 'instanceof' operand 'x'
      70. TypeError: invalid Array.prototype.sort argument
      71. TypeError: invalid assignment to const "x"
      72. TypeError: More arguments needed
      73. TypeError: property "x" is non-configurable and can't be deleted
      74. TypeError: Reduce of empty array with no initial value
      75. TypeError: setting getter-only property "x"
      76. TypeError: X.prototype.y called on incompatible type
      77. URIError: malformed URI sequence
      78. Warning: -file- is being assigned a //# sourceMappingURL, but already
          has one
      79. Warning: 08/09 is not a legal ECMA-262 octal constant
      80. Warning: Date.prototype.toLocaleFormat is deprecated
      81. Warning: expression closures are deprecated
      82. Warning: String.x is deprecated; use String.prototype.x instead
      83. Warning: unreachable code after return statement

 14. Misc
      1. JavaScript technologies overview
      2. Lexical grammar
      3. Iteration protocols
      4. Strict mode
      5. Template literals
      6. Trailing commas
      7. Deprecated features


IN THIS ARTICLE

 * Try it
 * Syntax
 * Description
 * Examples
 * Specifications
 * Browser compatibility
 * See also


REST PARAMETERS

The rest parameter syntax allows a function to accept an indefinite number of
arguments as an array, providing a way to represent variadic functions in
JavaScript.


TRY IT




SYNTAX

function f(a, b, ...theArgs) {
  // …
}


Copy to Clipboard


DESCRIPTION

A function definition's last parameter can be prefixed with ... (three U+002E
FULL STOP characters), which will cause all remaining (user supplied) parameters
to be placed within an Array object.

function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a);
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs);
}

myFun("one", "two", "three", "four", "five", "six");

// Console Output:
// a, one
// b, two
// manyMoreArgs, ["three", "four", "five", "six"]


Copy to Clipboard

A function definition can only have one rest parameter, and the rest parameter
must be the last parameter in the function definition.

function wrong1(...one, ...wrong) {}
function wrong2(...wrong, arg2, arg3) {}


Copy to Clipboard

The rest parameter is not counted towards the function's length property.


THE DIFFERENCE BETWEEN REST PARAMETERS AND THE ARGUMENTS OBJECT

There are three main differences between rest parameters and the arguments
object:

 * The arguments object is not a real array, while rest parameters are Array
   instances, meaning methods like sort(), map(), forEach() or pop() can be
   applied on it directly.
 * The arguments object has the additional (deprecated) callee property.
 * In a non-strict function with simple parameters, the arguments object syncs
   its indices with the values of parameters. The rest parameter array never
   updates its value when the named parameters are re-assigned.
 * The rest parameter bundles all the extra parameters into a single array, but
   does not contain any named argument defined before the ...restParam. The
   arguments object contains all of the parameters — including the parameters in
   the ...restParam array — bundled into one array-like object.


EXAMPLES




USING REST PARAMETERS

In this example, the first argument is mapped to a and the second to b, so these
named arguments are used as normal.

However, the third argument, manyMoreArgs, will be an array that contains the
third, fourth, fifth, sixth, …, nth — as many arguments as the user specifies.

function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a);
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs);
}

myFun("one", "two", "three", "four", "five", "six");

// a, "one"
// b, "two"
// manyMoreArgs, ["three", "four", "five", "six"] <-- an array


Copy to Clipboard

Below, even though there is just one value, the last argument still gets put
into an array.

// Using the same function definition from example above

myFun("one", "two", "three");

// a, "one"
// b, "two"
// manyMoreArgs, ["three"] <-- an array with just one value


Copy to Clipboard

Below, the third argument isn't provided, but manyMoreArgs is still an array
(albeit an empty one).

// Using the same function definition from example above

myFun("one", "two");

// a, "one"
// b, "two"
// manyMoreArgs, [] <-- still an array


Copy to Clipboard

Below, only one argument is provided, so b gets the default value undefined, but
manyMoreArgs is still an empty array.

// Using the same function definition from example above

myFun("one");

// a, "one"
// b, undefined
// manyMoreArgs, [] <-- still an array


Copy to Clipboard


ARGUMENT LENGTH

Since theArgs is an array, a count of its elements is given by the length
property. If the function's only parameter is a rest parameter,
restParams.length will be equal to arguments.length.

function fun1(...theArgs) {
  console.log(theArgs.length);
}

fun1(); // 0
fun1(5); // 1
fun1(5, 6, 7); // 3


Copy to Clipboard


USING REST PARAMETERS IN COMBINATION WITH ORDINARY PARAMETERS

In the next example, a rest parameter is used to collect all parameters after
the first parameter into an array. Each one of the parameter values collected
into the array is then multiplied by the first parameter, and the array is
returned:

function multiply(multiplier, ...theArgs) {
  return theArgs.map((element) => multiplier * element);
}

const arr = multiply(2, 15, 25, 42);
console.log(arr); // [30, 50, 84]


Copy to Clipboard


FROM ARGUMENTS TO AN ARRAY

Array methods can be used on rest parameters, but not on the arguments object:

function sortRestArgs(...theArgs) {
  const sortedArgs = theArgs.sort();
  return sortedArgs;
}

console.log(sortRestArgs(5, 3, 7, 1)); // 1, 3, 5, 7

function sortArguments() {
  const sortedArgs = arguments.sort();
  return sortedArgs; // this will never happen
}

console.log(sortArguments(5, 3, 7, 1));
// throws a TypeError (arguments.sort is not a function)


Copy to Clipboard

Rest parameters were introduced to reduce the boilerplate code that was commonly
used for converting a set of arguments to an array.

Before rest parameters, arguments need to be converted to a normal array before
calling array methods on them:

function fn(a, b) {
  const normalArray = Array.prototype.slice.call(arguments);
  // — or —
  const normalArray2 = [].slice.call(arguments);
  // — or —
  const normalArrayFrom = Array.from(arguments);

  const first = normalArray.shift(); // OK, gives the first argument
  const firstBad = arguments.shift(); // ERROR (arguments is not a normal array)
}


Copy to Clipboard

Now, you can easily gain access to a normal array using a rest parameter:

function fn(...args) {
  const normalArray = args;
  const first = normalArray.shift(); // OK, gives the first argument
}


Copy to Clipboard


SPECIFICATIONS

SpecificationECMAScript Language Specification
# sec-function-definitions


BROWSER COMPATIBILITY

Report problems with this compatibility data on GitHub

desktopmobileserver
Chrome

Edge

Firefox

Opera

Safari

Chrome Android

Firefox for Android

Opera Android

Safari on iOS

Samsung Internet

WebView Android

Deno

Node.js

Rest parameters
Full support
Chrome47
Toggle history
Full support
Edge12
Toggle history
Full support
Firefox15
Toggle history
Full support
Opera34
Toggle history
Full support
Safari10
Toggle history
Full support
Chrome Android47
Toggle history
Full support
Firefox for Android15
Toggle history
Full support
Opera Android34
Toggle history
Full support
Safari on iOS10
Toggle history
Full support
Samsung Internet5.0
Toggle history
Full support
WebView Android47
Toggle history
Full support
Deno1.0
Toggle history
Full support
Node.js6.0.0
more
Toggle history
Destructuring rest parameters
Full support
Chrome49
Toggle history
Full support
Edge79
Toggle history
Full support
Firefox52
Toggle history
Full support
Opera36
Toggle history
Full support
Safari10
Toggle history
Full support
Chrome Android49
Toggle history
Full support
Firefox for Android52
Toggle history
Full support
Opera Android36
Toggle history
Full support
Safari on iOS10
Toggle history
Full support
Samsung Internet5.0
Toggle history
Full support
WebView Android49
Toggle history
Full support
Deno1.0
Toggle history
Full support
Node.js6.0.0
Toggle history


LEGEND

Tip: you can click/tap on a cell for more information.

Full supportFull support
No supportNo support
User must explicitly enable this feature.
Has more compatibility info.
The compatibility table on this page is generated from structured data. If you'd
like to contribute to the data, please check out
https://github.com/mdn/browser-compat-data and send us a pull request.


SEE ALSO

 * Spread syntax (also '...')
 * Destructuring assignment
 * arguments object
 * Array


FOUND A PROBLEM WITH THIS PAGE?

 * Edit on GitHub
 * Source on GitHub
 * Report a problem with this content on GitHub
 * Want to fix the problem yourself? Learn how to contribute!

Last modified: Dec 13, 2022, by MDN contributors

MDN logo

Your blueprint for a better internet.

 * MDN on Twitter
 * MDN on GitHub


MDN

 * About
 * Hacks Blog
 * Careers


SUPPORT

 * Product help
 * Report an issue


OUR COMMUNITIES

 * MDN Community
 * MDN Forum
 * MDN Chat


DEVELOPERS

 * Web Technologies
 * Learn Web Development
 * MDN Plus

Mozilla logo
 * Website Privacy Notice
 * Cookies
 * Legal
 * Community Participation Guidelines

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2022 by individual mozilla.org contributors.
Content available under a Creative Commons license.