Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a Javascript function return objects by reference or value by default?

I have an object defined outside the function, in a global scope. This object is not passed into the function as an argument, but the function does modify it and return the modified object.

What I wanted to know is, if the function returns a copy of the object, or the original global object?

Also, will passing that object to the function as an argument, make a difference, since objects are passed into functions by reference?

like image 916
Hammad Akhwand Avatar asked Feb 21 '13 15:02

Hammad Akhwand


1 Answers

Whenever you're returning an object, you're returning a reference to the object. Likewise, when you're passing an object, you're passing a reference. However, passing an object in as an argument can be different than just changing an object in global scope, as these examples show. This is because the reference to the object is itself passed by value.

If you're changing the members of an object, then whether you pass it in as an argument or just update the global object makes no difference. Either way, you're working with the same object.

Example 1:

var object = {foo:'original'};  function changeObject() {     object.foo = 'changed';     return object; }  console.log(changeObject()); // outputs {foo:'changed'} console.log(object); // outputs {foo:'changed'} 

Example 2:

var object = {foo:'original'};  function changeArgument(object) {     object.foo = 'changed';     return object; }  console.log(changeArgument(object));  // outputs {foo:'changed'} console.log(object);  // outputs {foo:'changed'} 

On the other hand, if you're overwriting the object with a new object, the change won't persist if you do it to the argument, but will persist if you do it to the global object. That's because the argument passes the reference to the object by value. Once you replace this value with a reference to a new object, you're not talking about the same object anymore.

Example 3:

var object = {foo:'original'};  function replaceObject() {     object = {foo:'changed'};     return object; }  console.log(replaceObject()); // outputs {foo:'changed'} console.log(object); // outputs {foo:'changed'} 

Example 4:

var object = {foo:'original'};  function replaceArgument(object) {     object = {foo:'changed'};     return object; }  console.log(replaceArgument(object)); // outputs {foo:'changed'} console.log(object); // outputs {foo:'original'} 
like image 95
Tim Goodman Avatar answered Sep 19 '22 17:09

Tim Goodman