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.
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.