var a = 2;
var b = a;
console.log( b ); //2
a= 5;
console.log( b ); //2
Q: Why variable 'b' is getting value 2 even when variable 'a' is assigned a different value
var a = 2;
var b = a;
console.log( b ); //2
a= 5;
console.log( b ); //2
Q: Why variable 'b' is getting value 2 even when variable 'a' is assigned a different value
console.log(b)
returns 2
because when you access a primitive type you work directly on its value.
Cause numbers are immutable.
Changing an immutable value, replaces the original value with a new value, hence the original value is not changed (thats why b = 2
).
If you need a reference, use object and/or arrays
var a ={value: 2}, b = a
a.value = 3 // also changes the value of be, since it can mutate
In javascript, primitives (number, bool, string) are assigned by value, only objects are assigned by reference.
In Javascript, integers are immutable
. It means that the object's value once assigned cannot change. When you do
a=5;
b=a;
It is true that both are names of the same object whose value is 5
.
Later when you do -
a=2
It assigns the reference a
a new object whose value is 2. So essentially a
now points to a new object. Ans both objects exist.
For a better understanding you can refer to this link
When doing Assignment of primitive values in javascript:
It's important to point out that this assignment does not tie a
and b
together. In fact all that happened was that the value from a
was copied into b
, so when we go to change a
we don't have to worry about affecting b
. This is because the two variables are backed by two distinct memory locations – with no crossover.
In brief way:
When you assign b = a
Actually you didn't copy the reference of a
variable and make b
point to the same variable location in memory.
You only copy the value of a
variable and put it in new variable b
with different memory location.