Assign new array in ES6: Mutate an Array Declared with const

Tell us what’s happening:
Hi,
I have a question about modifying the array. Since we have numbered saved in a array 2, 5, 7, why we can’t use those numbers/indexes to assign new array?
Why is the only way to assign in this way:
const s = [5, 7, 2];
function editInPlace() {
“use strict”;
s[0] = 2;
s[1] = 5;
s[2] = 7;
}
editInPlace();

Your code so far


const s = [5, 7, 2];
function editInPlace() {
'use strict';
// Only change code below this line

// Using s = [2, 5, 7] would be invalid
s[0] = s[2];
s[1] = s[0];
s[2] = s[1];

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

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36.

Challenge: Mutate an Array Declared with const

Link to the challenge:

the issue here is that on line 2 the value of s[0] is no more the original one, and also on line 3 the value of s[1] is no more the original one, so that doesn’t give the result you want.
Try it, you get [2, 2, 2]

one thing you can do instead would be to use array destructuring

[s[2], s[0], s[1]] = s;

I think you meet it later in the curriculum.

or if your only objective is to put them in a certain order, there is also methods that order arrays, without having to do it manually.

1 Like

Thank you for replying :slight_smile: