javascriptvariablesmemoryimmutabilityprimitive

What prevents JavaScript primitives from being mutated?


In C, after declaring and initializing a primitive, we're able to access the memory address where the primitive is stored and directly modify its value. However in JavaScript it is said that primitive values are immutable. Once a string, for example, is created, it is not possible to modify it.

My question is what is preventing us from simply accessing the memory location where the value is stored and directly mutating the value? Is it just convention?

I read elsewhere that when variables are assigned primitive values in JavaScript, the variable points to a pre-determined memory location that represents the primitive value being assigned, rather than an arbitrary location in memory that holds the value specified. For example if I write:

let a = 3;
let b = 3;

Both a and b should point to the same memory address that represents the value 3. Therefore, it wouldn't make sense to say the memory address that JS interprets as the value 3 now holds the value 4. But I'm not sure I understand this notion. How can there ever be enough memory locations to represent all possible primitives out there? Surely I'm misunderstanding something.


Solution

  • Both a and b should point to the same memory address that represents the value 3

    That's not true. Both a and b point to memory addresses that hold the value 3. Whether or not this is the same address is entirely up to the JavaScript runtime.

    How can there ever be enough memory locations to represent all possible primitives out there?

    The memory for "all primitive values" isn't pre-allocated. JavaScript allocates memory as it's required. And indeed, it may run out. Consider the following:

    const arr = [];
    for (let i = 0; i < SOME_HUGE_VALUE; ++i) {
       arr.push(i);
    }
    

    Nothing in this example can be garbage-collected, so JavaScript is forced to keep adding values to arr. With a sufficiently large size, this will indeed crash.