Thursday, June 20, 2013

JavaScript Pass by Value or Pass by Reference

In languages like C#, Java
Pass by Value: Any modification on the parameter will not be seen by the caller.
Pass by Ref: All modifications including assigning a new object is seen by the caller.
function changeStuff(num, obj1, obj2, obj3)
{
    num = num * 10;
    obj1.item = "changed";
    obj2 = {item: "changed"};
    obj3.item = "changed";
    obj3 = {item: "something"};
    obj3.item = "something new";
}

Console:
var num = 10;
var obj1 = new Object();
obj1.item = "unchanged";
var obj2 = new Object();
obj2.item = "unchanged";
var obj3 = new Object();
obj3.item = "unchanged";
changeStuff(num, obj1, obj2, obj3);
console.log(num);
console.log(obj1.item);    
console.log(obj2.item);
console.log(obj3.item);

Output:
10
changed
unchanged
changed
Note: The above code snippet was taken from stackoverflow

In JavaScript, You can think of everything as objects even the primitive types like the parameter num above. Since, Javascript is a dynamic language you are allowed to add properties on the fly. The way you see the memory management in Javascript is a little different from their C#, Java counterparts.

All parameters are actually doing Pass by Reference. I know this is debatable. But, what needs to be clearly understood is that when you assign a new object to the function parameter then the function parameter will move pointing to the new object, leaving the caller parameter to see all the changes done by the function parameter until the point of the switch.

Please pay closer attention to the output of obj3. Is this pass by value or pass by reference? It was pass by reference until a new object was assigned. Which means the caller sees all the changes until it was assigned with a new object. All changes done post the new object assignment has been scoped only upto the function call.

obj1 case is similar to obj3, just that there was no changes made to obj1 and the first operation was to set it to a new object. Hence, it acts like a Pass by Value.

If you understood then I would be glad. Please take a bow!

If you are not or if I added to the confusion, I would refer you to continue your google search.

No comments:

Post a Comment