-2

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,

Community
  • 1
  • 1
  • `a` and `b` are different variables and are assigned different values. – p.s.w.g Apr 26 '19 at 16:11
  • 1
    See also [Explaining Value vs. Reference in Javascript](https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0) and these related questions: [javascript variable reference/alias](https://stackoverflow.com/questions/1686990/javascript-variable-reference-alias), [Javascript equivalent of assign by reference?](https://stackoverflow.com/questions/6732589/javascript-equivalent-of-assign-by-reference), [Change value of passed variable in Javascript without return?](https://stackoverflow.com/questions/15728938/change-value-of-passed-variable-in-javascript-without-return). – p.s.w.g Apr 26 '19 at 16:18
  • Possible duplicate of [Javascript equivalent of assign by reference?](https://stackoverflow.com/questions/6732589/javascript-equivalent-of-assign-by-reference) – Bob Dalgleish Apr 26 '19 at 19:16

6 Answers6

3

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.

1

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.

Debabrata Patra
  • 498
  • 3
  • 15
1

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 }
ttous
  • 336
  • 1
  • 3
  • 12
0

Because you are giving a value of a, and that is 23. Then you are reassign a to be 46.

0

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

sabeen kanwal
  • 607
  • 1
  • 5
  • 16
0

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.