Thursday, May 8, 2014

By value or reference?

In JavaScript writing functions is easy. No need to declare return type, no need for argument types, In fact you don't even need to declare arguments! One might argue if all this freedom is actually a good thing. Freedom or not, it is important to understand the JS very basics and understand if what we pass into functions is passed by value or reference.

If you are familiar with Java the behaviour in JS will make sense to you. For all those confused however about how arguments are passed into functions I put together quick example that I hope is self explanatory. Consider the code:

var a = 100,
    b = "Homer",
    c = {
        firstName: "Homer"
    },
    d = {
        firstName: "Homer"
    },
    e = {
        firstName: "Homer"
    },
    f = {
        firstName: "Homer"
    }

function changeName(a1, a2, a3, a4, a5, a6) {
    a1 = 200;
    a2 = "Bart";
    a3.firstName = "Bart";
    a4 = {
        firstName: "Bart"
    };
    delete a5.firstName;
    delete a6;
}

changeName(a, b, c, d, e, f);
// output
console.log("a1:"+a); // 100
console.log("a2:"+b); // Homer
console.log("a3:"+c.firstName); // Bart
console.log("a4:"+d.firstName); // Homer
console.log("a5:"+e.firstName); // undefined
console.log("a6:"+f); // object


Ok, a and b are primitive types and these are obviously passed by value. References to objects are also passed by value. Confused? Let me explain..

Lets start with c, its a3 inside of function. Its an objects reference passed into a function. Inside we modify its property and it does modify original object c that a3 references.

Now da4 argument inside the function. Again reference to object with firstName property "Homer" is passed (by value) into a function as a4 argument. Inside the function we assign other object to a4 argument. From now on a4 is a reference to different object. Modify it all you want, d from outside won't be touched.

e and f are straightforward really. In case of a5 reference to firstName is deleted and in case of a6 the a6 reference pointing to original object is deleted. Original object stays however and can be accessed by still existing reference f from outside of function.

Understanding of all this is pretty fundamental I believe and getting it wrong might result in bugs and confusion. Luckily for us all its also fairly easy concept to grasp and as easy to experiment with.

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from JQuery Training in Chennai . or learn thru JQuery Training . or learn thru ES6 Online Training. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete