8

What do you make of this?

var x = {a: 1};         //=> {a: 1}
var y = Object.keys(x); //=> ['a']
x[y]                    //=> 1

if y = ['a'], x[y] is the same as doing x[['a']], right?

x[['a']];               //=> 1

x[[['a']]];             //=> 1

x[[[[[[[['a']]]]]]]];   //=> 1

Can someone explain what's happening here? Why does this work?

5
  • 6
    Probably the unprofessional format of the question is my guess. This is a pretty simple question, though. Commented May 28, 2015 at 8:48
  • @Qix, I am a srs pro ^.^ Commented May 28, 2015 at 8:49
  • 3
    How is it important how long you have been working with JavaScript? Try `` y.toString(), this should get you going ... Commented May 28, 2015 at 8:50
  • @Mithrandir it wouldn't be a surprising observation if I just started learning JavaScript last week. Commented May 28, 2015 at 8:51
  • Please stop editing my question and taking away my identity now. Commented May 29, 2015 at 17:20

3 Answers 3

13

Property names have to be strings. If you try to use an array as a property name, it gets its toString() method called implicitly. That generates a string containing a comma-separated list of its values.

> var array = ['a', 'b', 'c'];
undefined
> array.toString();
'a,b,c'

If you only have one value, then there aren't any commas.

> var array = ['a'];
undefined
> array.toString();
'a'
Sign up to request clarification or add additional context in comments.

2 Comments

coma so many comas. Javascript puts me in a coma sometimes. ;)
@Quentin, I'm not sure why you rolled back my edit. It actually demonstrates accessing the property with an array. Your answer only offers two examples of arr.toString(). Anyway, I've given an answer that shows an actual test case of the behavior you described.
-3

@Quentin suggests that property names are automatically converted to strings. Ok, I think he's onto something there, but giving two explicit arr.toString() examples doesn't really demonstrate accessing the property of an object using an array. I offered this as an edit to his post. However, he rolled it back.

Anyway, this demonstrates the implicit behavior much more evidently, imo.

var x = {'a,b,c': 1};

var y = ['a','b','c'];

x[y]; //=> 1

Comments

-6

I think it come from 2 facts :

  1. The JS engine type as it goes
  2. any JS object can be access "like" an array

so your

["a"] 

when used as a key will be "casted" to string, which give

a

Even

[[[[["a"]]]]].toString() == a // true

so your

x[y] 

end un as

x["a"]

1 Comment

No, because your examples are incorrect. a is not a string, to start.

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.