Search code examples
javascripthtmlobjectpass-by-referencepass-by-value

Are variables/objects passed by value and why can't I change object's property with variable in javascript?


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?


Solution

  • 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).