Why does this return as an empty array?

I cannot find a logical reason why this code would continue to produce an empty array. Any ideas?

  **Your code so far**
function copyMachine(arr, num) {
let newArr = [];
while (num >= 1) {
let adder = [...arr];
newArr = newArr.splice(0, 0, adder);
  num--;
}
return newArr;
}

console.log(copyMachine([true, false, true], 2));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36

Challenge: Copy an Array with the Spread Operator

Link to the challenge:

Check documentation about the splice method. It returns not that you expect.

I did read the documentation and couldn’t find a reason that this wouldn’t work.

What splice returns?

Why use splice anyways? There are more ideomatic ways to add a new element to an array.

Also, why use a while loop? A for loop is more ideomatic for iterating a fixed number of times.

Looks like the starter code’s written with the while loop :confused:

function copyMachine(arr, num) {
  let newArr = [];
  while (num >= 1) {
    // Only change code below this line

    // Only change code above this line
    num--;
  }
  return newArr;
}

console.log(copyMachine([true, false, true], 2));

Eww, gross

You’re trying to add something to the array at index 0. Since it’s empty and there’s nothing at index 0, it’s returning an empty array.

Splice and there being nothing at index 0 is not the problem. The following code works just fine:

function copyMachine(arr, num) {
let newArr = ;
while (num >= 1) {
newArr.splice(0, 0, […arr]);
num–;
}
return newArr;
}

console.log(copyMachine([true, false, true], 2));

The problem appears to occur as a result of attempting to assign a value to the array using =. What I don’t understand is why. Even though the assignment operator is unnecessary it should still work, right?

What is the return value of splice?

This is still a strange way to use splice.

This code does not work. I just tested it.
EDIT: it didn’t get copied correctly, it does work, my bad

Splice performs an operation on an array, so there’s no need to do newArr = newArr.splice(0, 0, adder);, once you write newArr.splice(0, 0, adder); the array will be modified. Using the assignment operator will return an empty array.

so the difference is that here you are assigning the return value of splice, which is… ?

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