Antonio Pavicevac-Ortiz
Antonio Pavicevac-Ortiz

Reputation: 7739

Why does this property assignment overwrite the prior property in JavaScript?

var foo = new Object();
var bar = new Object();
var map = new Object();

map[foo] = "foo";
map[bar] = "bar";

alert(map[foo]);  //This alerts bar, but what happens to foo?

This is one of those questions to help with your understanding of how keys are assigned in JS. Of course, I immediately tried the following:

for(var prop in map){

   console.log(prop + ' ' + map[prop]);

} //[object Object] bar undefined

And then simply:

map //This returns Object {[object Object]: "bar"}

What?

UPDATE: Thanks for the answers but what happened to foo? Is there some kind of delete mechanism happening I never heard of?

Upvotes: 0

Views: 60

Answers (2)

JAAulde
JAAulde

Reputation: 19560

When you use your objects foo and bar as property names, .toString() is implicitly run on them. So you end up with:

map['[object Object]'] = "foo";
map['[object Object]'] = "bar";

alert(map['[object Object]']);

Upvotes: 1

agconti
agconti

Reputation: 18113

Object bracket notation coerces the value its given to a string. Since your giving it an object, it calls the object's toString method and saves the key as [object Object].

Foo is overridden by bar because you are saving to the same key, [object Object].

Ie. your object looks like this:

{
  "[object Object]": "bar"
}

Upvotes: 3

Related Questions