Difference for primitive value type and reference type in function argument passing
Description
All function arguments in Javascript are passed by value.
The value from outside is copied into an argument.
Pass primitive value
If the value is primitive, then it acts just like a primitive variable copy. Changes to the local variable are not reflected outside of the function.
function addTen(num) {/*w w w. ja va2s . co m*/
num += 10;
return num;
}
var count = 20;
var result = addTen(count);
console.log(count); //20 - no change
console.log(result); //30
The code above generates the following result.
Pass reference value
If the value is a reference to an object, it acts like a reference variable copy. Changes to the local variable are reflected outside of the function.
function setName(obj) {//from w w w . j a va2s .c o m
obj.name = "XML";
}
var person = new Object();
person.name = "CSS";
console.log(person.name);
setName(person);
console.log(person.name); //"XML"
Inside the function, obj
and person
point to the same object.
obj is accessing the object by reference.
When the name property is changed inside the function,
this change is reflected outside the function.
The code above generates the following result.
Note
The reference variable inside function can be reassigned to a new value, as a result it no longer points the same object as the variable outside.
function setName(obj) {/*from ww w . j a v a2s. c o m*/
obj.name = "XML";
obj = new Object();
obj.name = "CSS";
}
var person = new Object();
person.name = "CSS";
console.log(person.name);
setName(person);
console.log(person.name); //"XML"
We can think of function arguments in Javascript as local variables.
The code above generates the following result.