Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
150
rated 0 times [  156] [ 6]  / answers: 1 / hits: 37815  / 12 Years ago, thu, february 21, 2013, 12:00:00

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?


More From » node.js

 Answers
17

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'}

[#80078] Wednesday, February 20, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaredsages

Total Points: 273
Total Questions: 97
Total Answers: 105

Location: French Southern and Antarctic Lands
Member since Fri, Jan 6, 2023
1 Year ago
jaredsages questions
;