1

i tried this following code but it alerts the old object name property? i know that objects are passed by reference but its passed by reference then the object which is changed inside the function should also be change outside the function isn't it?

function setName(obj) {
 obj.name = "raziq";
 obj = new Object();
 obj.name = "abdul";
}
var person = new Object();
setName(person);
alert(person.name); //still yields raziq

i am a bit confused if object is passed by reference then the new name should be alerted why is it still alert raziq as the name of the object ?

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
abdul raziq
  • 849
  • 1
  • 7
  • 11
  • Why are you creating a new object inside of setName? – Thomas Wood Sep 30 '13 at 05:04
  • @ThomasWood I would hazard a guess as for the purpose of illustrating the problem – Phil Sep 30 '13 at 05:06
  • to see if it changes the person object outside the function because if objects are passed by reference then the new object inside the function should be reflected outside the function isn't it? – abdul raziq Sep 30 '13 at 05:07
  • possible duplicate of [How does variable assignment work in JavaScript?](http://stackoverflow.com/questions/509579/how-does-variable-assignment-work-in-javascript) – Phil Sep 30 '13 at 05:08
  • i am not talking about assigning things and its not duplicate – abdul raziq Sep 30 '13 at 05:11
  • @abdulraziq You are most certainly talking about assigning things (`obj = new Object()`) and the second-last paragraph of the [top answer](http://stackoverflow.com/a/509614/283366) sufficiently answers your question. – Phil Sep 30 '13 at 05:13
  • 1
    Please read some answers in this [post](http://stackoverflow.com/q/17503475/1169519) – Teemu Sep 30 '13 at 05:14
  • 2
    possible duplicate of [Is JavaScript a pass-by-reference or pass-by-value language?](http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Felix Kling Sep 30 '13 at 05:15
  • See may answer to this other question for a full explanation: http://stackoverflow.com/questions/13506398/why-are-objects-values-captured-inside-function-calls/13508654#13508654 – slebetman Sep 30 '13 at 05:48

3 Answers3

3

In your code:

> function setName(obj) {

The value of the first argument in the call is assigned to local variable obj. If an object is passed, the value of obj is a reference to that object.

>   obj.name = "raziq";

This will assign the value "raziq" to the name property of the object passed to obj. If the name property doesn't exist, it's created.

>   obj = new Object(); 

This assigns a new object reference as the value of obj, so it no longer references the object passed to the function.

>   obj.name = "abdul";

This assigns the value "abdul" to the name property (creating the property if it doesn't exist) of the object referenced by obj (the new one created and assigned in the line above).

Since there is no other reference to this object, it is made available for garbage collection as soon as the function ends.

> }
>
> var person = new Object();

Creates a new object and assigns it to the variable person. The value of person is a reference to the new object.

> setName(person);

Calls setName and passes it the object created on the line above. The function assigns raziq to the name property of the object (see above).

> alert(person.name); //still yields raziq

Alerts the value of the name property of the object created above and assigned to person. Since raziq was assigned as the value, that's what is returned.

Note that a new object is created in the function and a name property is created in an assignment statement, but the object isn't assigned anywhere or return it from the function, so everything after:

  obj = new Object();

effectively does nothing.

Note that it is more common to write:

  obj = {};

which has exactly the same result as the previous line, but is less to type and more widely used so likely (marginally) easier to read and maintain.

RobG
  • 142,382
  • 31
  • 172
  • 209
2

When you assign the new Object() to the variable obj, you're not actually swapping the original object. The computer creates a new spot in memory for the object you just instantiated and assigns the name property a value of "abdul", but that doesn't change the previous object, as it resides in a different spot in memory. The newly created object never leaves the function.

Instead of thinking of the obj variable as a container holding the object, think of it as a place holder with the numeric address of the location of the object. When you pass person in to the function, you're passing that address, not the object itself. So, inside of the function, when you create the new object, you're storing the address of that new object in the placeholder obj. The variable person outside the function still contains the address to the original object, not the new one you created in the function.

THEtheChad
  • 2,372
  • 1
  • 16
  • 20
  • isn't objects passed by reference ? – abdul raziq Sep 30 '13 at 05:13
  • 4
    @abdul: No. The *value* that is passed is a reference to the object, but that is not called "pass-by-reference". That's still "pass-by-value". See https://en.wikipedia.org/wiki/Pass_by_reference#Call_by_reference. – Felix Kling Sep 30 '13 at 05:16
  • 1
    Yes, but the function is using a copy of the ADDRESS to reference the object. When you change the variable inside the function, you're changing the address. – THEtheChad Sep 30 '13 at 05:16
  • so the objects reference is copied in the function ? – abdul raziq Sep 30 '13 at 05:23
  • so why is the first line in the function changes the object ? i mean – abdul raziq Sep 30 '13 at 05:24
  • 2
    @abdul: It changes the property of the object. Why? Because `obj` is a reference to the object, as we just mentioned. If JS was pass-by-reference, `person` would refer to the same object you created with `obj = new Object();`, but it doesn't. I really recommend to read the Wikipedia article I linked too, it describes the differences quite well IMO. – Felix Kling Sep 30 '13 at 05:26
  • on more question if i create a variable in side function without var keyword and assign it new object shouldn't it be global object ? – abdul raziq Sep 30 '13 at 05:33
  • 2
    @abdulraziq Yes, unless you use var, you're creating a new global variable. There's one exception, though, if you use the name of one of your parameters, you're not using a global var. Example `function foo(a){a = 7}` is merely recycling the variable `a` that was used by the parameter and is not creating a new global var. – THEtheChad Sep 30 '13 at 05:38
2

There is no "pass by reference" available in JavaScript. You can pass an object (which is to say, you can pass-by-value a reference to an object) and then have a function modify the object contents.

Source for reference

In JavaScript, we have functions and we have arguments that we pass into those functions. But how JavaScript handles what you’re passing in is not always clear. When you start getting into object-oriented development, you may find yourself perplexed over why you have access to values sometimes but not other times.

When passing in a primitive type variable like a string or a number, the value is passed in by value. This means that any changes to that variable while in the function are completely separate from anything that happens outside the function. Let’s take a look at the following example:

function myfunction(x)
{
      // x is equal to 4
      x = 5;
      // x is now equal to 5
}

var x = 4;
alert(x); // x is equal to 4
myfunction(x); 
alert(x); // x is still equal to 4

Passing in an object, however, passes it in by reference. In this case, any property of that object is accessible within the function. Let’s take a look at another example:

function myobject()
{
    this.value = 5;
}
var o = new myobject();
alert(o.value); // o.value = 5
function objectchanger(fnc)
{
    fnc.value = 6;
}
objectchanger(o);
alert(o.value); // o.value is now equal to 6

So, what happens when you pass in a method of an object? Most would expect (or at least I did) that it would be passed by reference allowing the method to access other parts of the object it is apart of. Unfortunately, that’s not the case. Check out this example:

function myobject()
{
    this.value = 5;
}
myobject.prototype.add = function()
{
    this.value++;
}
var o = new myobject();
alert(o.value); // o.value = 5
o.add();
alert(o.value); // o.value = 6
function objectchanger(fnc)
{
    fnc(); // runs the function being passed in
}
objectchanger(o.add);
alert(o.value); // sorry, still just 6

The problem here is the use of the ‘this’ keyword. It’s a handy short-hand for referring to the current object context. When passing a function as a parameter, though, the context is lost. More accurately, this now refers to the context of the object making the call instead of the object’s function we just passed in. For standalone functions, this would be the window object and for functions called from an event, this would be the event object.

Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
  • 1
    *"Passing in an object, however, passes it in by reference."* No! JavaScript is **always** pass by value. It just happens that in case of an object, a reference to the object is passed. However, that is not pass by reference. Pass by reference would be `var foo = 42; (function(baz) { baz = baz / 2}(foo)); alert(foo); /* would alert 21 */`, but that's not how JS works. – Felix Kling Sep 30 '13 at 05:37
  • @FelixKling: That's not exactly pass by value either. True pass by value (like in languages such as tcl) would have copied the entire object. I prefer to call this "pass by copy of reference" which is what you are saying. When you consider that javascript always passes a copy of the reference (or, in your terminology, the value of the reference) then it always behaves the same - even for numbers and strings. – slebetman Sep 30 '13 at 05:55