besseddrest
besseddrest

Reputation: 155

Array with 1 element is evaluated as that element when in brackets

const items = ['one'];
const obj = {
  'one': 'foobar'
};
console.log(obj[items]);

The console output is "foobar".

Why/how does [items] evaluate to "one"? Will this throw an error in strict mode?

Upvotes: 2

Views: 31

Answers (1)

vittore
vittore

Reputation: 17589

You cannot have a key of type Array. So your array is converted to string first and code is equivalent to

const items = ['one'];
const obj = {
  'one': 'foobar'
};
console.log(obj[items.toString()]);

Interestingly it would not work if you will try to add Symbol to your items array.

Also, because of the way Array.toString works, you can have items with multiple elements, and still get the same behaviour:

const items = [1,2];

const obj = {
   '1,2': 'foobar'
}

console.log(obj[items]); // also works

Upvotes: 4

Related Questions