What is spread operator doing to a function and why is it needed here?

function steamrollArray(arr) {
  const flattenedArray = [];
  // Loop over array contents
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      // Recursively flatten entries that are arrays
      //  and push into the flattenedArray
    } else {
      // Copy contents that are not arrays
  return flattenedArray;

// test here
steamrollArray([1, [2], [3, [[4]]]]);

In this example, when it gets to the second element, the if condition is true and then we recursively call the function again and pass in an array with one element 2 looking like [2]. Then the if condition is false and so pushes 2 to flattenedArray.

I think you can answer your own question here by testing a few simple examples. You can enter this right into the Console tab of your browser’s dev tools.

let arr = [1,2,3];

What does arr equal after this push? Notice this is the same thing that is happening in the if block of flattenedArray.


What happens when you push the array without using the spread operator?

But that still doesn’t explain why it’s called on a function rather than an array. Because the function is a push parameter it implies that it will eventually receive a return value and that returned value will be pushed to flattenedArray. But it does not seem like there is a return value. What is that return value?

It is being called on an array. What type of value does steamrollArray always return? There is only one return statement in the function so this should be an easy answer :slight_smile:

Javascript first executes the function steamrollArray() to get the return value and then applies the spread to the returned value.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.