0

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!

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.