-2

I just went through my class note and not really understood

var x = 1;
function func1() 
{
    x+= 10; 
}
func2 = function( x ) 
{ 
    x += 5;
}

what does the line func2 = function( x ) means? does x will be 15?

  • 1
    Asked and answered. E.g., http://stackoverflow.com/questions/336859/var-functionname-function-vs-function-functionname –  Sep 13 '13 at 23:18
  • so many vote down I really searched and didnt find the answer.. thanks anyway but im still not sure if func2 will update x – Chris Humpry Sep 13 '13 at 23:25
  • 1
    func2 will not update the value of the global `var x` because x is a local variable of func2. Variables declared as arguments of a function are local variables. It may have the same identifier, but it points to a different object. –  Sep 13 '13 at 23:27

1 Answers1

0

When you pass arguments that are primitives to functions they are passed by value. But if you pass in an argument that is an object it is passed by reference.

function myfunction(x)
{
    // x is equal to 4
    x = 5;
   // x is now equal to 5
}

var x = 4;
alert(x); // x is equal to 4

myfunction(x); 
alert(x); // x is still equal to 4

function myobject()
{
    this.value = 5;
}

var o = new myobject();
alert(o.value); // o.value = 5

function objectchanger(fnc)
{
    fnc.value = 6;
}

objectchanger(o);
alert(o.value); // o.value is now equal to 6