Look, there are lots of sources that will say that I'm wrong (and perhaps I am) - for example:
When assigning a primitive value to a variable or passing it as an argument to a function, its content is copied.
While this superficially works as a mental model (especially if you are trying to avoid talking about references) it makes no sense if all primitive values are immutable - duplicating immutable values is simply wasteful.
The "content is copied" mindset fosters the view that "variables point to the same memory address for their entire lifetime" - for example:
letx=123;// Content for variable `x` will always // live at address `#a` so:// #a: 123lety=x;// Content for variable `y` will always // live at address `#b` // and content is copied, so:// #a: 123// #b: 123y+=1;// We only change the content for `y`, so:// #a: 123// #b: 124//// Note that the value at `#b` changed. // This violates the assertion // that primitive values are immutable.
Compare that to the "variables just point to values" mindset:
letx=123;// Create a new immutable value at memory location `#a` // and have `x` point to it: // #a: 123// x: #alety=x;// `y` needs to point to the same value as `x` // so just _copy the reference_:// #a: 123// x: #a// y: #ay+=1;// Primitive values are immutable // so we create the new value `124` // and store it at memory location `#b` // and have `y` refer to it: // #a: 123// #b: 124// x: #a// y: #b
The thing is the "variables just point to values" view simplifies everything because now variables work exactly the same for primitive and non-primitive values and it also explains the behaviour of const - const makes the reference used by the variable immutable, so you're stuck with the same primitive or non-primitive value for the lifetime of that variable; however that doesn't affect the internal mutability of non-primitive values.
Look, there are lots of sources that will say that I'm wrong (and perhaps I am) - for example:
While this superficially works as a mental model (especially if you are trying to avoid talking about references) it makes no sense if all primitive values are immutable - duplicating immutable values is simply wasteful.
From What Does it Mean that Primitive Values are Immutable in JavaScript?:
The "content is copied" mindset fosters the view that "variables point to the same memory address for their entire lifetime" - for example:
Compare that to the "variables just point to values" mindset:
The thing is the "variables just point to values" view simplifies everything because now variables work exactly the same for primitive and non-primitive values and it also explains the behaviour of
const
-const
makes the reference used by the variable immutable, so you're stuck with the same primitive or non-primitive value for the lifetime of that variable; however that doesn't affect the internal mutability of non-primitive values.That was some great explanation, thanks for taking out the time to explain it so clearly.