javascriptfunctionparameter-passing

Understanding functions in javascript


I played with javascript and this is it :

> var obj = new Object();

> obj
{}
> obj.x = 0;
0
> function change_x(o) { o.x = o.x + 1; }

> change_x(obj);

> obj
{ x: 1 }
> function change_obj(o) { o = null; }

> change_obj(obj);

> obj
{ x: 1 }

function change_obj_x(o) { console.log(o); o.x = o.x + 1; o = null; console.log(o); }

> change_x(obj)

> change_obj_x(obj);
{ x: 2 }
null

> obj
{ x: 3 }

When i passed obj to change_x, it made changes into the obj itself, but when i tried to make obj null by passing it to change_obj, it did not changed the obj. Nor change_obj_x did what i expected.

Please explain this and give me some links to know everything about functions.


Solution

  • When you assign something to o in a function like in

    function change_obj(o) { o = null; }
    

    you don't change the parameter but just assign null to the variable. As the o variable doesn't exists outside the function, nothing happens.

    In contrast,

    function change_x(o) { o.x = o.x + 1; }
    

    changes the parameter itself. As the parameter is passed by reference, the value of the x property is also changed outside the function.

    In your function function change_obj_x(o), you combine these two effects. At first, you change the x property of o (which references to your obj), and then you assign null to o. The latter doesn't influence obj.