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)
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With