let a = 7; a = 3; console.log(a); // output 3
In this case, the value 7 is still inside a memory? I was reading that all primitive data types are immutable.
Advertisement
Answer
The value of a
is kept in memory, until garbage collection eventually recycles it. What the docs mean by immutable is that you can’t directly alter the primative (in this case the integer 7). You can only replace the value.
There are examples on the docs but this is another one
let a = 1; a.toString() // a is still 1, it cannot be mutated
However, we can assign this to another variable
let a = 1; let b = a.toString() // b is string "1" and a remains as the integer 1
Or we can replace the value
let a = 1; a = 10; // a is 10