I’m working on Step 4 where it asks: Log the grocery list to the console one more time. Notice that the groceryList array still contains the same items it had in Step 2.
The original groceryList was:
let groceryList = [‘orange juice’, ‘bananas’, ‘coffee beans’, ‘brown rice’, ‘pasta’, ‘coconut oil’, ‘plantains’];
As it mentions in the instructions, when you log groceryList to the console, it shows the array that was left from step 2 where it asked you to use .unshift(); and replace ‘orange juice’ with ‘popcorn’ so groceryList.unshift(‘popcorn’); gave this result:
How come the last step doesn’t revert back to the original array that had the orange juice or the .shift() method from Step 1 where it didn’t have ‘orange juice’ or ‘popcorn’ at all? Why does it skip over the array from Step 1 and go directly to the array in step 2?
At the start of step 2 ‘orange juice’ was gone. We replace it with ‘popcorn’ which is still present. The focal point of the lesson is that the slice is merely a copy of the selected range of the array. Nothing in the original array is affected and it remains completely intact.
A slice is a copy. That’s the bottom line.
slice is a copy
This is nice to know if we wish to spin off a true independent copy of an array.
Thank you but I understood the .slice() method. After the original array, the lesson asks you to do 1. a groceryList.shift(); 2. a groceryList.unshift(‘popcorn’); and 3. a groceryList.slice(1,4) which was more of a console.log(groceryList(1,4));
When you in input the last step console.log(groceryList); then it gives you the array it had on Step 2. This is the part I don’t understand. How does it decide it will still include Step 2’s list?
this is really a usefull answer.
I’m still confused tho about .slice() function, hope you can provide an answer one more time.
So when you call const tonicToFourth = fullArray.slice(0, 4);
why does it give you [ 'do', 're', 'mi', 'fa' ] ?
why doesnt it give you [ 'do', 're', 'mi', 'fa', 'sol' ] ?
since 0 = 'do' , 1 = 're' , 2 = 'mi' , 3 = 'fa' , 4 = 'sol' .
I think what was confusing is the fact that with the methods .shift() and .unshift(), the array will be modified while .slice() won’t modify the array and is just a copy of the array as you say. The lesson doesn’t explicitly tell you which ones out of the group of methods will modify and won’t modify an array (with the exception of .pop() and .push()). That’s something that you have to look up on your own to really understand this lesson.