Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript pass by reference? [duplicate]

Does JavaScript pass by references or pass by values?

Here is an example from JavaScript: The Good Parts. I am very confused about the my parameter for the rectangle function. It is actually undefined, and redefined inside the function. There are no original reference. If I remove it from the function parameter, the inside area function is not able to access it.

Is it a closure? But no function is returned.

var shape = function (config) {     var that = {};     that.name = config.name || "";     that.area = function () {         return 0;     };     return that; };  var rectangle = function (config, my) {     my = my || {};     my.l = config.length || 1;     my.w = config.width || 1;     var that = shape(config);     that.area = function () {         return my.l * my.w;     };     return that; };  myShape = shape({     name: "Unhnown" });  myRec = rectangle({     name: "Rectangle",     length: 4,     width: 6 });  console.log(myShape.name + " area is " + myShape.area() + " " + myRec.name + " area is " + myRec.area()); 
like image 265
J Any Avatar asked Oct 27 '12 21:10

J Any


People also ask

Does JavaScript pass by reference or copy?

In Javascript objects and arrays are passed by reference.

Does passing by reference make a copy?

The point of "pass by reference" is to not make a copy as soon as Employee constructor is called, but only when you choose to initialize one of Employee's member with the Date passed.

Is JavaScript always pass by reference?

Yes, Javascript always passes by value, but in an array or object, the value is a reference to it, so you can 'change' the contents.

Are JavaScript objects passed by value or pass by reference?

Javascript always pass by value so changing the value of the variable never changes the underlying primitive (String or number). In the following example, variable 'a' has assigned value 1.


1 Answers

Primitives are passed by value, and Objects are passed by "copy of a reference".

Specifically, when you pass an object (or array) you are (invisibly) passing a reference to that object, and it is possible to modify the contents of that object, but if you attempt to overwrite the reference it will not affect the copy of the reference held by the caller - i.e. the reference itself is passed by value:

function replace(ref) {     ref = {};           // this code does _not_ affect the object passed }  function update(ref) {     ref.key = 'newvalue';  // this code _does_ affect the _contents_ of the object }  var a = { key: 'value' }; replace(a);  // a still has its original value - it's unmodfied update(a);   // the _contents_ of 'a' are changed 
like image 163
Alnitak Avatar answered Oct 12 '22 00:10

Alnitak