0

I'd like understand why this difference (I suppose works like Java, so it's stack and heap difference)

var a = 10;
console.log(a);//10
function ChangeVal(){ b=a; b++; }
console.log(a);//10

var a = {name:"MyName"};
console.log(a);//{name:"MyName"}
function ChangeVal(){ b=a; b.name = "YourName"; }
console.log(a);//{name:"YourName"}
Donovant
  • 3,091
  • 8
  • 40
  • 68

1 Answers1

2

Assigning the value of one variable to another always involves copying the value. Thus:

b = a;

assigns the value of variable "a" to the (global! you forgot var!) variable "b". That happens in both your examples.

In the first example, the value of "a" is the number 10. In the second, it's a reference to an object. After

b = a;

in both cases, the variable "b" has the same value — a copy of the same value — as "a".

Because one reference to a particular object is as good as another, in your second example it's perfectly natural that changing the value of the "name" property on that object can be done via the reference in either "a" or "b".

Pointy
  • 405,095
  • 59
  • 585
  • 614