Reputation: 4108
var items = new Array("one", "two", "three");
var itemsRef = items;
items.push("four");
console.debug(itemRef);
console.debug(items);
I really dont get the idea how above items
and itemsRef
are same even items added "four" when after itemsRef
referenced items
. Isn't it reasonable that itemsRef
should have only ("one" "two" "three")?
If itemsRef
keep pointing items
forever, why do we use such an useless argument like items = itemsRef
? I am still not getting the idea. Can anybody tell me how this is works and why JavaScript let variables pointing each other forever?
Upvotes: 1
Views: 89
Reputation: 3343
In this case itemsRef is not pointing at items, but rather at the object (array) items reference is pointed at. In other word, items and itemsRef point to the same object and not each other.
Upvotes: 1
Reputation: 11633
Javascript makes assignments of Objects and Arrays by reference instead of by value/copy. That's why you're seeing that behavior. There's plenty of web documentation about that.
But if your goal is to copy an array, do this:
var newArray = oldArray.slice(0);
Upvotes: 4