Copy an Array with the Spread Operator mine

Tell us what’s happening:

plz i need an explanation for my code

Your code so far

function copyMachine(arr, num) {
  let newArr = [];
  while (num >= 1) {
    // change code below this line
newArr=[[...arr], ...newArr]//here is wat i did, need a summary about this
    // change code above this line
  return newArr;

// change code here to test different cases:
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/71.0.3578.98 Safari/537.36.

Link to the challenge:

The spread operator takes a iterable collection of values and gives you them back one-by-one.

An iterable is something you can iterate over in order, so an array in this case - the first value is at position 0, second is at position 1, and so on.

So you have an array:

const myArray = [1,2,3,4]

And ...myArray will basically give you back those values one-by-one if you ask it to. So with


You are saying “give me the values from myArray one-by-one, and put them in a new array”.

This also means you can use the ... take the values from different arrays an shove them into new arrays:

const myArray1 = [1,2,3];
const myArray2 = [4,5,6];
// Take the values from the first aray and the second array
// and put them all in a new array:
const myNewArray = [...myArray1, ...myArray2]

So you are copying (cloning) the values from one array to another array.

Keeping that in mind, your code:

function copyMachine(arr, num) {
  let newArr = [];
  while (num >= 1) {
    newArr=[[...arr], ...newArr]
  return newArr;

So to walk through it step-by step, assuming you are executing the function like this:

copyMachine([true, false, true], 2)


arr = [true, false, true]
num = 2

newArr = []

# num >= 1, so
# 1. [...arr] means take the values from `arr` and put in new array
# 2. ...newArr means take the current values from `newArr` and put them in a new array
# newArr is [], so there is nothing to add for 2
newArr = [[true, false, true]]

NOTE newArr now has a single value in it: an array ([true, false, true])

num = 1

newArr = [[true, false, true]]

# num >= 1, so:
newArr = [[true, false, true], [true, false, true]]
num = 0;

newArr = [[true, false, true], [true, false, true]]

# num < 1, so:
return [[true, false, true], [true, false, true]]
1 Like