So In Javascript Docs They Said The All Primitives Are Immutable
so my question is
when i write let x = 'foo';
x = 'bar'
;
is this mean that a foo Is In a spererate memory location
and bar in another memory location and the garbage collection will collect the old one which is foo
or is it just replacing the value of foo to bar in the same memory location which is firstly defined ?
2
Answers
You are bang on here, the old value and the new value occupy separate memory locations.
Say
x = 'foo'
,foo
is stored in one memory location.When you then do
x = 'bar'
,bar
is stored in a different memory location, and x now points to that new location and then the old value ‘foo’ becomes eligible for garbage collection.Hence in Javascript, primitives are immutable, each new assignment creating a new value in memory rather than modifying an existing one.
Yes, but that’s not unique to primitives, that would happen with an object too. If you do:
The new object is stored at another memory location and the first one can be garbage collected (assuming nothing else is referring to it).
When they say that primitives are immutable, they mean something else. They mean you cannot make changes to that spot in memory. For example,
x.toUpperCase()
can’t change what’s stored in the existing string, it can only return you a new string. Or if you do this:You’ll either get an error in strict mode, or nothing will happen in non-strict mode.
In contrast, objects can be mutated. You can make changes to what they contain, while still keeping them at the same spot in memory: