Kuldeep Kashyap
Kuldeep Kashyap

Reputation: 33

How bracket notation in javascript access the property of an object?

Consider below example:

a={
  'firstProperty': "first", 
  'secondProperty':"second"
};
console.log(a[[[["firstProperty"]]]]);

by using multiple bracket notation i am able to access the firstProperty. How bracket notation is accessing this property??

Upvotes: 0

Views: 135

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386550

You are using a nested array and by using a non string or symbol as value, the value is converted to string.

console.log([[["firstProperty"]]].toString());

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074058

Because what you provide as the key in a property accessor expression is converted to string if it isn't a Symbol or a string. console.log(a[[[["firstProperty"]]]]); uses an array of arrays as the property name in the accessor expression. Since that isn't a Symbol, it's converted to string. When you convert your array to string, you get the string "firstProperty" because that's how Array.prototype.toString works:

console.log(String([[["firstProperty"]]]));

...and "firstProperty" correctly identifies one of the properties in the object, so the property accessor expression gives you the value of that property.

Using an array like that is unnecessary. Just use

console.log(a["firstProperty"]);

or

console.log(a.firstProperty);

Upvotes: 1

Related Questions