Rest Operator Question

Learning some ES6 stuff.

How do you get around the fact that when an array is passed in, the length of the array now changes to 1. You cannot access each index. Seems to destroy the usefulness a bit?


var printArr = function(...arr) {
    console.log("What is the length: " + arr.length);    //---> Output: 1  (This has 5 values actually)
    console.log(`Value of index 2:  ${arr[2]}`);   //---> Output: Undefined

myArr = [1, 7, 14, 21, 28];

If you pass in a single argument, you will have an array with one single element, it is useful so that the function can accept any number of arguments. So all the arguments are stored in the parameter arr

For example, a function to sum any number of elements

Check your first console log. It outputs array within array.

    console.log(`Value of index 2:  ${arr[0][2]}`);   //---> Output: Value of index 2:  14

One way to go about this is to spread array items when calling function:

1 Like

But what I’m trying to say that once the array is passed in, you can longer access each specifc index. Something appears to happen to the array in a negative way.

I already understand the benefit of multiple indefinite values, this is similar to *args in Python.

Ah I see, that’s what’s happening. Thank you.

You pass in an array, so that array becomes arr[0], the first element of the passed in array is arr[0][0]

If only one argument is passed in (in this case an array) the rest operator is not necessary, but it is useful if you want a function with any number of arguments passed in