JavaScript
x
4
1
let a = 7;
2
a = 3;
3
console.log(a); // output 3
4
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
JavaScript
1
3
1
let a = 1;
2
a.toString() // a is still 1, it cannot be mutated
3
However, we can assign this to another variable
JavaScript
1
3
1
let a = 1;
2
let b = a.toString() // b is string "1" and a remains as the integer 1
3
Or we can replace the value
JavaScript
1
3
1
let a = 1;
2
a = 10; // a is 10
3