When I initialize an array with an object in JavaScript, does the array contain a reference to the object or is it passed by value?

StackOverflow https://stackoverflow.com/questions/17828857

Question

I am using JavaScript. I have an object. I then place that object inside an array that I initialize. I then do some work on that array and the value(s) inside it. I'm hoping to know if, by changing the object in the array, I am also changing the actual object itself? Code below.

function doStuff() {
    var node = getNode(); //getNode() returns a node object
    var queue = [node]; //This is the line my question is about

    while(queue.length > 0) {
        //Add data to queue[0]. Add queue[0]'s children to queue, remove queue[0]
    }

    return node;
};

So, when the while loop finishes, will node be pointing to the changed object, or will it just hold a copy of the object from before it was put into the queue?

I appreciate any help, many thanks!

Was it helpful?

Solution 2

You could check it yourself:

var obj = {a: 1, b: 1};
var arr = [obj];
arr[0].a = 0;
alert(obj.a) // Result: 0;

http://jsfiddle.net/pnMxQ/

OTHER TIPS

Objects in Javascript are always assigned by reference, they're never copied automatically.

I have an object. I then place that object inside an array that I initialize.

No, you don't. "Objects" are not values in JavaScript. You have a reference (pointer to an object). You place that inside the array. node is a reference. queue is a reference. getNode() returns a reference. Once you realize that, it becomes simple.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top