Javascript - Function Function Argument

Introduction

All function arguments in ECMAScript are passed by value.

The value outside of the function is copied into an argument on the inside of the function.

If the value is primitive, then it acts just like a primitive variable copy, and if the value is a reference, it acts just like a reference variable copy.

When an argument is passed by value, the value is copied into a local variable.

When an argument is passed by reference, the location of the value in memory is stored into a local variable, which means that changes to the local variable are reflected outside of the function.

Consider the following example:

function addTen(num) {
   num += 10;
   return num;
}

var count = 20;
var result = addTen(count);
console.log(count);    //20 - no change
console.log(result);   //30

Here, the function addTen() has an argument num, which is essentially a local variable.

When called, the variable count is passed in as an argument.

This variable has a value of 20, which is copied into the argument num for use inside of addTen().

Within the function, the argument num has its value changed by adding 10, but this doesn't change the original variable count outside of the function.

Pass by reference value

Consider the following code

function setName(obj) {
   obj.name = "First";
}
var person = new Object();
setName(person);
console.log(person.name);    //"First"

In this code, an object is created and stored in the variable person.

This object is then passed into the setName() method, where it is copied into obj.

Inside the function, obj and person both point to the same object.

When the name property is set on obj inside the function, this change is reflected outside the function.

Related Topics

Quiz