Modify an array using slice()

In the solution below:
Are we reassigning the arr array in function ?
so why we still get same value for arr?

  **My Code:**

function forecast(arr) {
  // Only change code below this line
arr = arr.slice(2,4);
  return arr;
}
const weather = ['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']
// Only change code above this line
console.log(forecast(weather));
weather ;
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36

Challenge: Copy Array Items Using slice()

Link to the challenge:

Hi @SinaBoby !

Slice returns a shallow copy of the orginal array. It doesn’t modify it.

That’s why this console.log returns a new array

console.log(forecast(weather));

Whereas this console.log prints the original array

console.log(weather)

If you want to make changes to the original array then you would use splice.

Hope that makes sense!

thanks for your answer , actually I know what it does but my question is that if inside the function we say arr = arr.slice() so we basically reassigned the arr value . it like we say

let myNumber = 2 ;
myNumber +=2;
console.log(myNumber); => 4 ;

so why in the question , the value of arr doen’t change while reassign it with arr.slice() value which is [‘rain’,‘snow’] for example?

I personally wouldn’t take this approach of writing arr = arr.slice() and then returning arr on the next line.

It would be simpler and cleaner for understanding purposes to just return it all in one line.

  return arr.slice(2, 4);

That’s just my two cents :grinning:

1 Like

Hi Sina,

I am not sure if I understand your question correctly but when you use arr = arr.slice you reassign the value already (advice don’t reasing the values with the same name - is more confusing…)

Remember javascript is single-threaded so it reads your code line by line in order.

Please try this on your code and you will see:

function forecast(arr) {
  console.log('first',arr)
  arr = arr.slice(2, 4)
  console.log('second',arr)
  return arr;
}

hope that helps

1 Like