Cannot understand the following line in question

I am on the following link and here it says

const s = [5, 6, 7];
s = [1, 2, 3];
s[2] = 45;
console.log(s);

s = [1, 2, 3] will result in an error. The console.log will display the value [5, 6, 45].

when I ran the code in the console

const s = [5, 6, 7];
s = [1, 2, 3];
s[2] = 45;
console.log(s);

I got an error

VM182:2 Uncaught TypeError: Assignment to constant variable.
at :2:3
I am very much confused why the question says “s = [1, 2, 3] will result in an error. The console.log will display the value [5, 6, 45].” because it gives me an error

When you declare a variable with const, you can not assign the variable to a new value, that is why when you write s = [1, 2, 3] it errors out with the message it does.

Thanks. shouldn’t it be like following the question

The code will not reach the last two lines because it errors out. If you remove or comment out the 2nd line, it will work because the 4th line is not assigning a new value to s. It is changing the value the 3rd element of the array s.

Arrays and Objects are different than primitive values such as Strings and Numbers.
When you create an array like const s = [5, 6, 7], you are actually assigning a reference to the array’s memory location. When you try to assign another array to s, JavaScript refuses because using const will in essence freeze that memory location and not allow anything else to be assigned to it. The elements of the array can be changed or deleted and are not affected by using const.

I agree with the OP. It is unclear, to some extent, that you have to comment out the line.

This is the original

s = [1, 2, 3] will result in an error. The console.log will display the value [5, 6, 45].

I’d use:

s = [1, 2, 3] will result in an error. After commenting out that line, the console.log will display the value [5, 6, 45].

Sounds good. Why not create an issue or PR on GitHub to get the text changed?

1 Like

Alright, I will, thanks.