javascriptmemorymemory-management

What's Mean Immutability in javascript


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 ?


Solution

  • 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

    Yes, but that's not unique to primitives, that would happen with an object too. If you do:

    let x = { foo: 'foo' };
    x = { bar: 'bar' };
    

    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:

    //'use strict';
    let a = 1;
    a.nickname = 'alpha';
    console.log(a.nickname);

    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:

    let x = { foo: 'foo' };
    let y = x; // Create another way to refer to the same spot in memory
    x.bar = 'bar';
    console.log(x); // Includes .bar
    console.log(y); // Also include .bar, since it's the same object, which has been mutated.