If “let” prevents the variable from being modified…
let
does not prevent the variables from being changed.
let
allows variables to be changed.
You’re thinking of const
.
And it’s super important to understand that const
only sort of prevents variables from being changed.
In particular, const
prevents things like numbers and strings from being mutated, and it does prevent an object or array from being reassigned, but it is important to note that the contents of the object or array can still be mutated!
So if you tried to run this,
const a = 8, b = 6;
(() => {
"use strict";
[b, a] = [a, b];
})();
console.log(a);
console.log(b);
then you will get a TypeError: invalid assignment to const 'b'
message.
However, the following will actually work:
const arr = [8, 6]; // in this case the array itself is const,
// but it's _contents_ are mutable!
(() => {
"use strict";
[arr[1], arr[0]] = [arr[0], arr[1]];
})();
console.log(arr[0]); // is now 6
console.log(arr[1]); // is now 8
But if I try to do this:
const arr = [8, 6]; // in this case the array itself is const,
// but it's _contents_ are mutable!
arr = [8, 6]
then I will get a TypeError: invalid assignment to const 'arr'
error.
Think of const arr
as a house’s address. You can rearrange the furniture inside the house without any problems, and you can even renovate the house itself, but you can’t just replace the ground the house is on (i.e. the address of).
So, this would be like replacing the ground the house is built on:
const sesameStreet123 = []
sesameStreet123 = []
And it will cause an error.
But, this is like renovating in the house:
const sesameStreet123 = ['kitchen', 'bathroom', 'bedroom']
sesameStreet123.push('master bedroom')
And it will work just fine.
Hope that helps you out 