2
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

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
adi
  • 187
  • 1
  • 2
  • 10

5 Answers5

2

console.log(b) returns 2 because when you access a primitive type you work directly on its value.

Damien
  • 1,582
  • 1
  • 13
  • 24
1

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

Thomas Wikman
  • 696
  • 4
  • 11
1

In javascript, primitives (number, bool, string) are assigned by value, only objects are assigned by reference.

Thiatt
  • 564
  • 1
  • 6
  • 21
1

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

97amarnathk
  • 957
  • 2
  • 11
  • 30
1

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.

Oghli
  • 2,200
  • 1
  • 15
  • 37