If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Primitive values immutable or not?

There is a fundamental difference in JavaScript between primitive values (undefined, null, booleans, numbers, and strings) and objects (including arrays and functions). Primitives are immutable: there is no way to change (or “mutate”) a primitive value.

Based on my understanding of this, it isn't so much that you are changing the value of let's say 'myvar', but you are setting it to an entirely new value. The original value is erased entirely and it is replaced with something new. For objects you are actually changing values as the object itself remains intact (otherwise you'd lose all other information within the object).

Hopefully that helps clear up the difference between primitive values and objects.

"Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

you can reassign a variable at will, that's no biggie.
what you can't do is modify it without the re-assignment, or simply without using the "=" char...

with an array, you can say x=[1,2,3]; x.reverse(); alert(x[0]); to see 3.
you can't do that with a string: all the String.prototoype method like bold() and replace() return new strings: the value to the left of the dot that's to the left of the method call never changes, even if something different comes out of the right-hand side of the method call.

contrast this with arrays, where a pop() or push() changes the value to the left of the dot that's to the left of the method call.

one more way of saying it: if something is immutable, you cannot create a prototype method that alters the 'this' value, only one that returns something new.

this is related to, but not the same as the passing byRef and byVal effects described in post #3.

Last edited by rnd me; 01-04-2013 at 03:01 AM.

Create, Share, and Debug HTML pages and snippets with a cool new web app I helped create: pagedemos.com