Dynamic Arguments

Rest Parameters and Arguments

Todd Motto by Todd Motto Google Developer Expert Icon Google Developer Expert
JavaScript Icon

Learn JavaScript the right way

Premium JavaScript courses to skyrocket your skills to the top.

5x Courses: Basics, Masterclass, HTML5 APIs, DOM, Testing with Jest.

As data passed into functions can be dynamic, it could have an unknown number of arguments.

What do we mean by this?

The same function could accept one argument, two, three, four:

renderDrinks('Water', 'Coffee');
renderDrinks('Water', 'Coffee', 'Lemonade');

How could we achieve this?

It would be ideal to access the arguments dynamically, regardless of how many are passed.

A naive approach would be to attempt something like this:

// ❌ Not a good approach
function renderDrinks(drinkOne, drinkTwo, drinkThree) {}

This would quickly get messy when safety checking each argument given, perhaps there’s a better way.

First, there’s the traditional arguments object, which would allow us to remove the function parameters:

function renderDrinks() {
  // Arguments ['Water', 'Coffee', 'Lemonade', callee: ƒ, Symbol(Symbol.iterator): ƒ]

renderDrinks('Water', 'Coffee', 'Lemonade');

This arguments object is a special built-in class that provides us an iterable, array-like, data structure that contains our arguments in order.

It also has special properties like arguments.length.

It’s common to use the spread operator to copy the arguments into a new array, which then gives us full Array.prototype powers:

function renderDrinks() {
  // Array ['Water', 'Coffee', 'Lemonade']

renderDrinks('Water', 'Coffee', 'Lemonade');

At this point, you could iterate through the array and render out each item.

That’s the “traditional” way of dynamically accessing arguments, but ES2015 (ES6) introduced the “rest parameter” which should be our preferred method.

The design of this feature is far more intuitive and looks a lot more pure:

function renderDrinks(...drinks) {
  // Array ['Water', 'Coffee', 'Lemonade']

renderDrinks('Water', 'Coffee', 'Lemonade');

Notice how it automatically gives us an array as well. A win-win for clean and concise code.

At this point we’ve learned the ins and outs of JavaScript functions, their parameters and arguments, and are ready to start getting more advanced.

Parameters and Arguments

« Function Parameters and Defaults

Short and Long Syntax

Implicit and Explicit Return Statements »