What are rest parameters and rest variables in JavaScript?

A JavaScript rest parameter consists of the rest operator (...), and a regular parameter name. The rest parameter can only be present as the last argument to a function.

A visual representation is shown below.

Rest parameter example

// Define a function with two regular parameters and one rest parameter:

function myFruits(fruit1, fruit2, ...otherFruits) { 
  return otherFruits;
}

The rest operator (...) instructs the computer to put the rest of some specific user-supplied arguments into an array. Thus, the remaining arguments can be accessed as part of the array, otherFruits.

As such, we call ...otherFruits a rest parameter.

Code

// Define a function with two regular parameters and one rest parameter:
function myFruits(fruit1, fruit2, ...otherFruits) {
return otherFruits;
}
// Invoke myFruits function while passing five arguments to its parameters:
const result = myFruits("mango", "strawberry", "apricot", "kiwi", "orange");
console.log(result);

Explanation

In the snippet above, myFruits was invoked by passing five arguments to the function.

In other words, "mango" and strawberry" got assigned to fruit1 and fruit2 respectively.

At the same time, the rest operator put the remaining arguments ("apricot", "kiwi", and "orange") into an array and assigned that array to the otherFruits parameter.

Rest variable in JS

A JavaScript rest variable consists of the rest operator and a regular variable. This is the same as with the rest parameter, except that this is applicable to lists used in a program generally and not just limited to parameters.

// Define a destructuring array with two regular variables and one rest variable:
const [name1, name2, ...otherNames] = [
"Nina", "Sarah", "Steve", "Mike", "Flora"
];
// Print the rest variable items:
console.log(otherNames);

Explanation

In this case, the rest operator (...) instructs the program to assign the remaining user-supplied values into an array titled otherNames. Thus, otherNames is a rest variable.

This can also be applied to array destructuring.

// Define a destructuring object with two regular variables and one rest variable:
const { name1, name2, ...otherNames } = {
name1: "Nina",
name2: "Sarah",
name3: "Steve",
name4: "Mike",
name5: "Flora"
}
// Invoke the otherNames variable:
console.log(otherNames);
// The invocation above will return:
// {name3: "Steve", name4: "Mike", name5: "Flora"}

Free Resources

Attributions:
  1. undefined by undefined