Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript confusion over variables defined by reference vs value

I understand the following property of the javascript language:

var bar = 1;
var foo = bar;
bar = "something entirely different";
// foo is still 1

However, when trying to apply this logic to an object it seems to act differently:

var bar = {};
bar.prop = 1;
var foo = bar;
bar.prop = "something entirely different";
// foo.prop now changes to "something entirely different"
// but...
bar = "no longer an object";
// now foo remains an object with the prop property

Can someone tell me what's happening and why there is a difference?

like image 639
Jeff Avatar asked Nov 04 '22 04:11

Jeff


1 Answers

That's correct. When you assign a variable to an object, you're really creating a second reference to that object. In the first case, what you're doing is assigning bar to point at the string foo points to, but then you change what bar points to when you reassign bar.

In the second example, you assign bar to a new object, then you point foo at that same object, then you reassign bar to a string. foo is still pointed at the same object.

Think of it like this: bar = "something" is changing what bar points to, not changing the actual object {} to a string.

This article is a fairly good explanation of what you're seeing. I'm looking for even better / more authoritative references, however.

like image 105
Josh Avatar answered Nov 09 '22 11:11

Josh