Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How object referencing works in JavaScript? [duplicate]

Tags:

javascript

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)
like image 808
Varun r Avatar asked Apr 07 '26 00:04

Varun r


1 Answers

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}

like image 150
Code Maniac Avatar answered Apr 08 '26 12:04

Code Maniac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!