Do i need to do the assignment and why?

Why does this code work


function forecast(arr) {

// Only change code below this line
arr = arr.slice(0, 2)

return arr;
}

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

and this one doesn’t?


function forecast(arr) {

// Only change code below this line
arr.slice(0, 2)

return arr;
}

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

why do i need to assign it to itself in order for the code to work?
why doesnt it just process the arr.slice() using the argument that was passed to it, and then work after returning arr? Does it not recognize that returning arr is enough instructions?

Your browser information:

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

Challenge: Copy Array Items Using slice()

Link to the challenge:

.slice() does not modify the array.

1 Like

ah h that makes sense. You just opened my eyes that I was thinking it would have the same behavior as a method that DOES alter the array passed into it, like a splice() i would say, and so if that was a splice() method, then I wouldnt need to assign it to itself, correct?

And since it doesn’t modify they arrays you would need to get they array type that arr.slice() returns and assign it to your original array arr.

In this way you’re telling javascript that the sliced array is now what variable arr is.
On the next line you would then return what arr is which is the sliced array in the first code and the unmodified arr on the second code.

1 Like

so i would HAVE to re assign it inside the function , becuase its returning a completely different array?

You can also just return it, in this case.

...
return arr.slice(0, 2)
2 Likes

Ah yes, thank you. That’s what i was missing in my thinking. And it would work also by just returning because then you are applying the slice functionality to its returned value, correct?

1 Like

slice() returns a value. When you have a return statement, everything on the right is evaluated first, so arr.slice(0,2) resolves and the value that it returns is what your function returns.

1 Like

Right! It was the re assigning arr part that I was leaving out of my thinking

So then, let me ask you this, without re-assigning the variable to arr or any other variable, then what happens to it? What happens to it after you run that slice method on it? on the arr.slice() ? does it just get lost in memory? Or does nothing happen to it since it DOES NOT modify the existing array? Like basically nothing executes?

slice returns a new value.

if you want to use that value you need to capture it (storing it in a variable, returning it, etc)

slice execute anyways

1 Like

If you don’t assign it to a variable or return it, then the value isn’t saved anywhere.

1 Like