3

I'm new to JavaScript and I thought objects are passed by reference.

The output I expected was:

{ one: 1 } { one: 1 }
{ two: 2 } { two: 2 }

Output obtained:

{ one: 1 } { one: 1 }
{ two: 2 } { one: 1 }

When b is referencing address of a, why is b still { one: 1 }

var a = {one:1}
var b = a

console.log(a,b)

a = {two:2}

console.log(a,b)
Varun r
  • 85
  • 1
  • 1
  • 6

3 Answers3

5

when you did b = a, so now the b holds the same reference as of a

But when you assign a new value to a

a = { one : 2 }

It created a new memory reference for the value ( { one : 2 } ) and tag it with a variable, so you can refer to the memory reference using a and get the value. but b still holds the initial reference of a which has value {one : 1}

Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

Let's analyze this one by one:

var a = { one: 1 }  // 'a' points now to (example) location: #fff
var b = a        // 'b' points to the same location: #fff

Now, when you are asigning a new object to a:

a = { two: 2 }

a now points to new location in memory (say, #ff1) and it doesn't affect b's location, which still points to #fff. That is why the last console.log(a,b) call gives you { two: 2 } { one: 1 } output.

syntagma
  • 23,346
  • 16
  • 78
  • 134
1

When b is referencing address of a, why is b still { one: 1 }

Because b is not referencing the address of a, but both of them are referencing the address of object { one: 1 }. Then a starts referencing the address of a brand new, different object, { two: 2 }, and absolutely nothing changes about b, or the first object, { one: 1 }, which still remains intact and existing, exactly because b needs it.

tevemadar
  • 12,389
  • 3
  • 21
  • 49