Good day friends!
After checking the Hint to this challenge I passed the challenge but to be honest, I don’t quiet understood the logic behinde the solution.
I expected to see something like this
function copyMachine(arr, num) {
let newArr = [];
while (num >= 1) {
// Only change code below this line
//num == arr;
num = [...arr]; // Since I was to copy arr and make it num
newArr.push(num); // then I pushed num in to the newArr
// Only change code above this line
num--;
}
return newArr;
}
console.log(copyMachine([true, false, true], 2));
Please someone should help me with the explanation of the solution .
Why do we need to declare a new variable to hold the copy?
Thanks!
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 6.3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36.
Thanks!
Here is the correct solution to the challenge.
function copyMachine(arr, num) {
let newArr = [];
while (num >= 1) {
// Only change code below this line
//num == arr;
let newNum = [...arr]; // Why do I need this line?
newArr.push(newNum);
// Only change code above this line
num--;
}
return newArr;
}
console.log(copyMachine([true, false, true], 2));
In Javascript, roughly speaking, a variable can only hold one thing. If you want to hold an entire array, then Javascript puts the array in your computer’s memory and then stores the location of the array in your variable.
With
let myArray = [1, 2, 3];
let myNewArray = myArray;
both variables point to the same place in memory.
With
let myArray = [1, 2, 3];
let myNewArray = [...myArray];
the spread operator makes a copy the contents (top level contents, really) of the first array, then the []s mean the contents are stored in a new place for an array in memory, and then that new location for the copied array is stored to myNewArray.