Alex Rivera | Logout

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

Asked 2013-02-21T15:41:20.507
29

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?

Edit
Report

1 Answer

1

From your question this is how I think your code looks (more or less):

var o = {};

function f() {
    o.prop = true;
    return o;
}
  1. In this case the global variable o references an object.
  2. When you modify o you're modify whatever o references. Hence it modifies the original object.
  3. When you return o you're returning a reference to the original object.

Passing the object to a function results in the reference to the original object being passed. Hence any modifications will affect the original object. For example:

var o = {};

f(o);

console.log(o.prop); // true

function f(o) {
    o.prop = true;
}
answered 2013-02-21T15:56:54.617

Your Answer