4

I have this code

var myObjects = {}; //global variable

//Later on in the code:
for (i in myObjects)
{
    var obj = myObjects[i];
    process(obj);
}

function process(obj)
{
    $.getJSON("example.com/process/", {id: obj.id}, function(result)
      {
          //Will the following change the permanent/global copy e.g 
          // myObjects[44] ?
          obj.addItem(result.id, result.name, result.number);
      }
    );
}

Will the following line:

     obj.addItem(result.id, result.name, result.number);

modify the object by value or by reference, i.e will it modify the local copy of obj or e.g myObjects[44]?

If it affects only the local copy, how can I have it change the global copy of the object?

Ali
  • 261,656
  • 265
  • 575
  • 769

3 Answers3

4

Primitive variables are passed by value in JavaScript, but objects are passed by reference.

Source and further reading:

Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
  • 2
    Note that it's a little weirder than that: if you create a string by calling "new String('hi mom')" then it works kind-of like a string sometimes, but it'll act like an Object for parameter passing. That is, it's passed by reference. – Pointy Feb 15 '10 at 16:36
  • 1
    Actually, strings are immutable in js. Therefore, you are always passing them by reference. All operations on strings return a new string. – Ruan Mendes Feb 15 '10 at 19:39
  • 1
    In JavaScript, when you pass an object, you are really passing an object reference by value. See this [earlier question](http://stackoverflow.com/a/518069/379428). – Andrew Dec 10 '12 at 23:36
1

JavaScript is pass by value, as has been clarified in an earlier question. (Someone with more powers should mark this as duplicate--the answers here are incorrect.)

Community
  • 1
  • 1
Andrew
  • 5,611
  • 3
  • 27
  • 29
0

all non-object variables are pass-by-value afaik..

jellyfishtree
  • 1,811
  • 1
  • 10
  • 11