skip to Main Content

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


  1. 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

    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.

    Login or Signup to reply.
  2. 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.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search