My code:
var a = 23;
var b = a;
a = 46;
console.log(a);
console.log(b);
Why is the value of b printed as 23 and not as 46?
Output :
a=46, b=23,
My code:
var a = 23;
var b = a;
a = 46;
console.log(a);
console.log(b);
Why is the value of b printed as 23 and not as 46?
Output :
a=46, b=23,
In Javascript, Only Objects/Arrays are passed by reference and others are passed by value. As a and b hold integer values they are passed by value.
Look at this answer. Primitives are passed by values and objects are passed by reference. As a and b are primitives, they are passed by values. And when a is changed that will not be reflected in b.
When var b = a; is executed, b does not "refer" to a. It becomes a number whose value is a's value at this moment.
However, if you use an Object, the attribution will use the reference of a, and not its value:
a = { value: 23 };
b = a;
a.value = 46;
console.log(b);
// console
Object { value: 46 }
Because you are giving a value of a, and that is 23. Then you are reassign a to be 46.
in your code first you initialize a with value of 23 and then you assign value of a to b
var a = 23;
var b = a;
a = 46;
console.log(a);
console.log(b);
then you update value of a but not assigning it to b
As in Java-Script Only Objects/Arrays are passed by reference and others are passed by value. As a and b hold integer values they are passed by value.
so updating value of a did not result in change of b value ; if you assign value to b after updating value of a it would result in displaying value of 46 for both a and b
assignment operator means you assign the value of right side to the value of left side so by this statement var b = a; b becomes 23 and once you change a it has no affect on value of b due to lexical scoping of js.