My question is : why doesn’t myArray stay =[[“John”, 23], [“cat”, 2]];
I mean we do the .push() step, but doesn’t it only relate to removedFromMyArray? It’s like the same as I write “const removedFromMyArray = [“cat”, 2]”; so why does this has to change myArray?
Your code so far
// Setup
const myArray = [["John", 23], ["cat", 2]];
// Only change code below this line
const removedFromMyArray = myArray.pop()
console.log(myArray)
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36
Challenge Information:
Basic JavaScript - Manipulate Arrays With pop Method
Because you are using the pop method const removedElement = myArray.pop();
Here pop not only returns the element to the removedElement it removed from myArray, but pop also mutates the array or modifies it directly. So myArray will never have the element in it that pop removes. If you want myArray to stay the same then you would want to make a copy of the array first
const copiedMyArray = [...myArray];
Then you can use the pop method on the copy of the array
const removedElement = copiedMyArray.pop();
This way the copy array is changed, and the original array stays the same
The variable name is also an indication, removedFromMyArray not copiedFromMyArray.
If you just want the first element (or any element) you can use the index for it and assign it to a variable. We also have the .at() method if you prefer that.
push and pop are used to work with arrays in memory, they do all the hard work for you so you do not have to manage the size of the array and the precise access to the location of the elements in memory. If they were non-mutating they wouldn’t be very useful.