Javascript Pass by Reference


Javascript pass reference by value for primitive value, and pass by reference for objects and array. You may modify the contents of the object. The object cannot be overwrote.

var arr=[1,3,5];
function f(a)
{
   a.push(7);
}
f(arr);
alert(arr.length);  //4, arr is 1,3,5,7

But the object can't be overwrote.

var arr=[1,3,5];
function f(a)
{
   a=[3,4];
}
f(arr);
alert(arr.length);  //3, arr is still 1,3,5

Similarly to the associative array.

var arr = {"city" : "New York", "country" : "USA"};
function f(a)
{
   a["city"] = "Seattle";
}
f(arr);
alert(arr["city"]);  //seattle
//////////////////////
arr = {"city" : "New York", "country" : "USA"};
function f(a)
{
   a["name"] = "David";
}
f(arr);
alert(arr.length);  //undefined

endmemo.com © 2024  | Terms of Use | Privacy | Home