Rest parameter and array methods

The rest parameter eliminates the need to check the args array and allows us to apply map() , filter() and reduce() on the parameters array.

What does the tutorial mean by this?

Challenge: Use the Rest Parameter with Function Parameters

Link to the challenge:

In the original code:

const sum = (x, y, z) => {
  const args = [x, y, z];

We had to create an array called args in order to use array methods (like.reduce()).

By changing the function signature to use the rest parameter, you don’t need to create an array inside the function because it is declared in the function signature.

2 Likes

We already have arguments which is usually called “array-like”. There are a few constructs in javascript that are referred to as being array-like, generally it means “I have a .length property and you can usually read things in me at given indexes.” Strings are a great example of array-like constructs.

Unlike arrays, array-like things don’t support array methods, and things at index positions are usually read-only.

We could do this same thing using arguments, in one of two ways:

const functionWithArgs = () =>{
  // javascript automatically creates arguments keyword
  const [...args] = arguments;

  // same thing another way
  const sameArgs = [...arguments];

}

Both approaches do the same thing. The first uses the rest operator to turn all the arguments into a true array; the second does the same with the spread operator (spreading the arguments into individual parameters within the []).

1 Like