- The primitive type such as
strings, numbers, booleansare pass-by value andobjectsis pass-by reference. pass-by valueis to pass a copy.pass-by referenceis to pass a pointer.
Example 1
- pass-by value
- The variable
ainfoofunction is only visible inside thefoofunction.
"use strict";
var a = 1;
function foo(a){
a = 2;
}
foo(a);
console.log(a); //1Example 2
- objects is pass-by reference.
"use strict";
var a = {};
function foo(a){
a.firstname = "Hiroko";
}
foo(a);
console.log(a); //{firstname: "Hiroko"}Example 3
- when you change the object, we have to change a property NOT an object itself.
"use strict";
var a = {"moo": "foo"};
function foo(a){
//a = {"moo": "goo"}; // we can't change a object. we can only change the property.
a.moo = 'goo';
}
foo(a);
console.log(a); //{moo: "goo"}