Slice method not working

Why is this code not working?

function forecast(arr) {

  // Only change code below this line
arr.slice(2, 4);
  return arr;


// Only change code above this line

console.log(forecast(['cold', 'rainy', 'warm', 'sunny', 'cool', 'thunderstorms']));
1 Like

Hello there,

For future posts, if you have a question about a specific challenge as it relates to your written code for that challenge, just click the Ask for Help button located on the challenge. It will create a new topic with all code you have written and include a link to the challenge also. You will still be able to ask any questions in the post before submitting it to the forum.

As for your problem, I suggest you research into what the slice method does:

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Thank you.

1 Like

Okay. I will take care the next time. Thank you.

slice does not mutate the array. It returns a new array, so we should grab the output.

let arr=[1,2,3,4]
let arrOut = arr.slice(1,3)
console.log("arr is ", arr, "\narrOut is: ", arrOut)

Beside of that, remember to experiment with the code. Run it on your console (press Shift+Control+K) for firefox.


function htmlColorNames(arr) {

arr.splice(0, 2)
return arr; // [‘DarkGoldenRoad’, ‘WhiteSmoke’];


console.log(htmlColorNames([‘DarkGoldenRod’, ‘WhiteSmoke’, ‘LavenderBlush’, ‘PaleTurquoise’, ‘FireBrick’]));

But if we try splice like this it works. Why do we have such different behaviors?

@harshitbadolla That’s another good question. Splice does mutate the array.

That’s the way they were build and each one has use cases. When in doubt, either play with the console or check mozilla docs.

MDN Splice

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

MDN Slice

The slice() method returns a shallow copy of a portion of an array into a new arrayBlockquote

1 Like

Alright. Now i got it. Thank you very much.