0

Suppose I have an object as:

var obj = {
        len: 4,
        bred: 5
    }

Now suppose I assign this object to a variable x as var x = obj;. As far as I understand it, it creates a copy of obj and assign that copy to x — that is pass by value. Now If I change a property of x then it changes that property of the obj object too. E.g.

x.len = 99

Then both obj.len and x.len become 99. On the other hand consider this scenario:

var r = 2, s = 3, t = 4; 
s = r;
s = 88;

Now r is passed by value to s that s a copy of r was given to s. So changing s to 88 doesn't change the original value of r variable. Typing r in the console still gives 2.

Question 1: If variables (objects included) are passed by value in JavaScript then why does changing x.len change the original obj.len, too?

Another problem is that I cannot change an object's property when assigning to a variable. Consider this scenario:

var obj2 = {
        len: 4,
        bred: 5
    }
var x2;
x2 = obj.len;

Now typing x2 in console simply returns 4. But if I try to change the value of x2 such as x2 = 77; then that doesn't change obj2.len.

Question2: Why can't I change object's property with a variable?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
user31782
  • 7,087
  • 14
  • 68
  • 143

2 Answers2

4

Everything is passed by value, but when you create an object you get an reference to that object.

// Create an object. Assign a reference to that object to `obj`
var obj = {
    len: 4,
    bred: 5
};
// Copy the value of `obj` to `x`. Now `x` is also a reference to that object.
var x = obj;

Any changes to properties of x or obj will now modify the same object because they go through copies of the same reference.


var obj2 = {
    len: 4,
    bred: 5
}
var x2;
x2 = obj.len;

len is a number, not an object, so the value isn't a reference. So when you copy it you get a copy of the number (instead of a copy of the reference to the object).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
2

Primitive types (strings, numbers, booleans, null, undefined and symbols) are passed by value; objects are also passed by value, but the value passed is that of their reference.

As far as I understand it, it creates a copy of obj and assign that copy to x -- that is pass by value.

No, x is assigned a copy of the value of the reference to obj. x then points to obj. Modifications made via either reference will then modify the same object.

obj.len, on the other hand, contains a primitive, so the value of itself is copied.

Ben Aston
  • 53,718
  • 65
  • 205
  • 331
nils
  • 25,734
  • 5
  • 70
  • 79