.slice question


Code is behaving. I’m just not understanding. How exactly does .slice work? (In very simple terms, please, I am so very new to this)
This exercise asked for “You’re in a hurry so you decide to ask a friend to help you with your grocery shopping. You want him to pick up the bananas, coffee beans, and brown rice.
Use .slice() to provide him with a list of these three things.
Log this part of the list to the console. Unlike the two previous checkpoints, you should do both of these steps in one line.”
My questions are

  1. why are there only two numbers (1, 4) in the .slice line when I’m supposed to be making a list of three things?
  2. The instructions ask for both steps in one line, but then it has console.log(groceryList); under it again. Is that just to print the whole list again?
    This is the code it gave me when I gave up, so this is what the lesson is asking for.

let groceryList = [‘orange juice’, ‘bananas’, ‘coffee beans’, ‘brown rice’, ‘pasta’, ‘coconut oil’, ‘plantains’];



console.log(groceryList.slice(1, 4));

because the two values are start and stop value (start value inclusive, stop value exclusive), using slice can give you an array of 5 of more elements, see mdn slice:

slice() produces a new list, the original list isn’t modified


Easy enough to slip into another language, in JS the objects are arrays

Think of a slice as a snapshot. This is a copying method, and nothing more.

Reference objects cannot be copied by direct assignment. All that gets assigned is a reference to that object. To get around this limitation on arrays, we use slice() to make a copy.

let cloned_array = original_array.slice();

There is a need to experiment with this to see how deep that copy will be. A flat array will copy in its entirety, but a nested array may not.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.