mgamer
mgamer

Reputation: 14050

Strange equality issue with Javascript object properties

Why after executing that snippet of code:

var a = {};
var b = {};

var g = {};
g[a] = "aa";
g[b] = "dd";

the value of g[a] is "dd"?

a == b is false so what is going on here?

Upvotes: 2

Views: 196

Answers (2)

Matt Ball
Matt Ball

Reputation: 359786

JavaScript object keys can only be strings. When you store g[a] = 'aa', a is converted to a string using the toString() method,1 so you're actually storing 'aa' at g[a.toString()].

In this case, a.toString() is '[object Object]', which is equal to b.toString().

To make it really obvious, the code in your question is equivalent to this:

var g = {};
g['[object Object]'] = 'aa';
g['[object Object]'] = 'dd';

Moral of the story: just don't try to use anything other than strings as property names.


1Source: MDC: JavaScript Member Operators - Property Names

Upvotes: 7

mattsven
mattsven

Reputation: 23253

a and b are objects, and you'd be using them as keys in doing g[a] or g[b], which can't work since associative arrays can only use valid variable names or strings as keys.

What are you trying to accomplish?

var a = "a";
var b = "b";

var g = {};
g[a] = "aa";
g[b] = "dd";

Would work properly, however.

Upvotes: 1

Related Questions