jshashtable states:
JavaScript's built-in objects do provide hashtable functionality using
the square brackets notation for
properties, provided your keys are
strings or numbers:
From what I know, keys are only strings, (since numbers are coerced into strings anyway). I just want to check and be sure that what is stated above is false (since keys can't be numbers).
Did the ECMA standard state anything about this?
Or is the implementation browser-specific?
Best Answer
That seems to be incorrect - object keys may be strings or (since ECMAScript 2015, aka ECMA-262 ed 6) symbols. But that is a different topic to square bracket property access.
See ECMA-262 ed 3 ยง 11.2.1 (Please also see ECMAScript 2017 (draft).):
So when using dot notation, the bit after the dot must fit the criteria for an IdentifierName. But when using square brackets, an expression is provided that is evaluated and resolved to a string.
Briefly, square bracket notation is provided so that properties can be accessed using an expression, e.g.
In the above,
x
is provided in square brackets so it is evaluated, returning the string 'foo'. Since this property doesn't exist ony
yet, it is added. Thefoo
property ofy
is then assigned a value of 'foo value'.In general terms, the expression in the square brackets is evaluated and its
toString()
method called. It is that value that is used as the property name.In the dot property access method, the identifier is not evaluated, so:
creates a property
bar
with a valuebar value
.If you want to create a numeric property, then:
will evaluate
5
, see it's not a string, call (more or less)Number(5).toString()
which returns the string5
, which is used for the property name. It is then assigned the value5
, which is a number.This answer was written when ECMAScript ed3 was current, however things have moved on. Please see later references and MDN.