Basic Data Structures - Copy Array Items Using slice()

Tell us what’s happening:
Solved the problem but why is it that it ends at 4? To my understanding, the end point (final value) does not get extracted/copied into the new var. So it should end at 3 not 4. Thx!

Your code so far

function forecast(arr) {
  // Only change code below this line

  return arr.slice(2, 4);
}

// Only change code above this line
console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.60

Challenge: Basic Data Structures - Copy Array Items Using slice()

Link to the challenge:

Ya, I always get tripped up on this one as well :slightly_smiling_face:

The first arg to slice is the beginning index in the array.

The second arg is the ending index in the array, but not really. It is more of “up to, but not including, the end”. So even though you pass in 4, you are really only including up to index 3 in the array.

Your solution is returning ['warm', 'sunny'] which are at index 2 and 3 in the array.

thx but you really didn’t answer my question

Ahh, sorry, I think I misread your question. If I am understanding correctly, you are asking why JS decided to make the second arg to slice exclusive instead of inclusive.

I don’t have an answer for this off the top of my head. I think that other languages also follow this approach, so there is probably a good explanation and hopefully someone can chime in here with it. But it also could just be “because that’s the way it’s always been done.”