Special Case/Question on "Mutate an Array Declared with const"

Tell us what’s happening:

I passed this challenge, but I was wondering why s=[2,5,7]; would be invalid? What if the array was much larger than 3 elements, say, 100 elements and you needed to change the first 50… would you need to change them separately, one at a time, like we did in this challenge? Is there a faster way?

Your code so far


const s = [5, 7, 2];
function editInPlace() {
  "use strict";
  // change code below this line
s[0]=2;
s[1]=5;
s[2]=7;
  // s = [2, 5, 7]; <- this is invalid

  // change code above this line
}
editInPlace();

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/mutate-an-array-declared-with-const

when you declare an array variable with const you are saying that you cannot re assign that variable to a different array, thus s = [2,5,7] is attempting to assign the variable s to another array with the values 0: 2, 1: 5, 2: 7 and it throws an error.

But the fun thing about arrays declared with const (and objects too) is that while you can’t just assign it a whole new array, you CAN change its contents. That is why s[0] = 2 and so on works. You are not trying to make a new array, you are just changing the contents of the existing array.

As far as faster ways, it really depends on what you are trying to do, but you can use loops and some of the fun array methods found here to do a bunch of fun things to your array.

1 Like

Thank you so much for your help!! :slight_smile: :slight_smile:

1 Like

To your hypothetical, off the top of my head I would probably create an enumerable of the 50 replacement values then iterate over them using Array.forEach() passing the index as well, and replace that index of s with the current value of our replacement array.

1 Like