Get stuck with: Copy an Array with the Spread Operator

Tell us what’s happening:

Why doesn’t my sollution work?

Your code so far


function copyMachine(arr, num) {
let newArr = [];
while (num >= 1) {
  // Only change code below this line
newArr = [..arr , num]; //sets newArr equl to true, false, true which should be stored in the spread opperator and 2 which should be stored in num variable 
  // Only change code above this line
  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/84.0.4147.125 Safari/537.36.

Challenge: Copy an Array with the Spread Operator

Link to the challenge:

  • num shouldnt be in the array, it’s just the number of copies.
  • the operator is ... so there is a dot missed

Come back if still confused.

1 Like

Yes still confused here…
The example shows how to copy it when i try to duplicate it i get a

TypeError: Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a Symbol.iterator method.
error

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

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

You are using the spread syntax on num, but num is not an array, so you cannot use the spread syntax. You can only use the spread syntax on the arr provided.

1 Like

The spread operator “spreads out” something that has multiple elements.* In your code, you are using the spread operator on something (num) that does not have multiple elements.

To elaborate:

let myArray = [1, 2, 3];

//let's use the spread operator now

let newArray = [...myArray];
console.log(newArray);

//[1,2,3] we've "spread out" the elements of myArray _into_ newArray, an empty array

//what if we didn't use the spread operator?

newArray = [myArray];
//[[1,2,3]] By plopping myArray straight into newArray, without the ..., it's an array in an array.

What if we try to use a regular number and the spread operator?

let num1 = 7;
newArray = [...num1]

//Uncaught TypeError: number 4 is not iterable (cannot read property Symbol(Symbol.iterator))
    at <anonymous>:1:1
Not allowed!  num1 is not an "iterable" element, it can't be spread.

hope this helps

2 Likes