Reputation: 32013
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!
Upvotes: 0
Views: 1015
Reputation: 122489
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.
Upvotes: 0
Reputation: 10140
You could check it yourself:
var obj = {a: 1, b: 1};
var arr = [obj];
arr[0].a = 0;
alert(obj.a) // Result: 0;
Upvotes: 0
Reputation: 782130
Objects in Javascript are always assigned by reference, they're never copied automatically.
Upvotes: 1