2

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?

1
  • JavaScript implementations might have some bizarre-hidden-ones. Which Browser / JavaScript engine are you testing with? Commented Apr 24, 2011 at 15:39

2 Answers 2

7

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

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

Comments

1

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.

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.