Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question
add comment (requires an account with 50 reputation)

3 Answers

up vote 0 down vote accepted

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/

share|improve this answer
add comment (requires an account with 50 reputation)

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

share|improve this answer
add comment (requires an account with 50 reputation)

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.

share|improve this answer
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.