3

Unintentionally, In my project I had used the following code and I was surprised to see that is working:

HTML

<span id="output"></span>

Javascript

var myObject = {
  'a': '----First---',
  'b': '----Second---',
  'c': '----Third----'
};

var myArray = ['a'];

// First Case
output.innerHTML = myObject[myArray];

var myArray2 = ['b'];

// Second Case
output.innerHTML += myObject[myArray2];

var myArray3 = ['a', 'b'];

// Third Case 
output.innerHTML += myObject[myArray3];

Output

----First-------Second---undefined

Jsbin Link: http://jsbin.com/godilosifu/1/edit?html,js,output

I am directly accessing array reference within Object which should be undefined in all the cases but strangely When array is of Size 1, it always gets the first element and use that as the object key.

I just want to know what is this concept called and why is this happening ?

Sachin Jain
  • 21,353
  • 33
  • 103
  • 168

3 Answers3

7

Because the property name has to be a string, it is type cast into one using the toString() method. The reason that your third example is undefined is that ['a', 'b'].toString() equals 'a,b', which is not a property in your object.

Property names

Property names must be strings. This means that non-string objects cannot be used as keys in the object. Any non-string object, including a number, is typecasted into a string via the toString method.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors

Worth noting is that in ECMAScript 6, there is a new collection type called Map, which allows you to use any object as a key without type coercion.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Drenmi
  • 8,492
  • 4
  • 42
  • 51
3

When you pass the array to the object as a Key, it is calling toString() on it. This is because all Keys in Javascript are Strings.

['a'].toString() is "a"
myObject['a'] is "----First----"

See: Keys in Javascript objects can only be strings?

Community
  • 1
  • 1
Upio
  • 1,364
  • 1
  • 12
  • 27
2

It's auto-casting. In Javascript, only strings can be indexes into an object's properties. myObject is not an array, it's an object. Even though you're using the brackets to access it's properties, it is not the same meaning as brackets used on an array object.

Due to object properties only being allowed to be named by strings, the compiler auto-casts your array to a string (essentially calling it's native toString() function, which for an array, joins all the elements with a comma).

So when you pass your array to the object's property accessor/index, it does this:

myArray1 ==> "a";
myArray2 ==> "b";
myArray3 ==> "a" + "," + "b" ===> "a,b";
Don Rhummy
  • 24,730
  • 42
  • 175
  • 330