Search code examples
javascriptfunctionvariablespass-by-referencepass-by-value

JavaScript setting value to variable properties on a function call


I found that there are these two ways that a variable property value can be updated on a function call

Example 1:

function bar( arg ) {
  return arg + 1;
}

var foo = {
  num: 1
};

foo.num = bar( foo.num );
console.log( foo.num );

Example 2:

function bar( arg ) {
  arg.num = arg.num + 1;
}

var foo = {
  num: 1
};

bar( foo );
console.log( foo.num );

I want to know what are the proper naming convention for each of the method calls.

Also can anyone explain, how it is possible to update the original variable value inside a closed function operation as shown in example 2?


Solution

  • Primitive parameters (such as a number) are passed to functions by value; the value is passed to the function, but if the function changes the value of the parameter, this change is not reflected globally or in the calling function.

    If you pass an object (i.e. a non-primitive value, such as Array or a user-defined object) as a parameter and the function changes the object's properties, that change is visible outside the function. Source : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

    Well in javascript objects are passed by reference so when you pass a object to a function you're passing it's memory reference not a copy. So when you update value in the function it updates the value at reference.

    function bar(arg) {
      arg.num = arg.num + 1;
    }
    
    var foo = {
      num: 1
    };
    
    bar(foo);
    console.log(foo.num);

    When you pass a primitive value it is passed by value. It passes a copy of value so whatever changes you do in close function will not affect the original value.

    function bar(arg) {
      arg = arg + 1;
    }
    
    var foo = 1
    
    bar(foo);
    console.log(foo);