Keys in Javascript objects can only be strings?

Solution 1:

JavaScript's built-in objects do provide hashtable functionality using the square brackets notation for properties, provided your keys are strings or numbers

That seems to be incorrect - object keys are always strings 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).):

Properties are accessed by name, using either the dot notation:

MemberExpression . IdentifierName

CallExpression . IdentifierName

or the bracket notation:

MemberExpression [ Expression ]

CallExpression [ Expression ]

The dot notation is explained by the following syntactic conversion:

MemberExpression . IdentifierName

is identical in its behaviour to

MemberExpression [ <identifier-name-string> ]

and similarly

CallExpression . IdentifierName

is identical in its behaviour to

CallExpression [ <identifier-name-string> ]

where <identifier-name-string> is a string literal containing the same sequence of characters after processing of Unicode escape sequences as the IdentifierName.

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.

var y = {};
var x = 'foo';
y[x] = 'foo value';

In the above, x is provided in square brackets so it is evaluated, returning the string 'foo'. Since this property doesn't exist on y yet, it is added. The foo property of y 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:

y.bar = 'bar value';

creates a property bar with a value bar value.

If you want to create a numeric property, then:

y[5] = 5;

will evaluate 5, see it's not a string, call (more or less) Number(5).toString() which returns the string 5, which is used for the property name. It is then assigned the value 5, which is a number.

Edit

This answer was written when ECMAScript ed3 was current, however things have moved on. Please see later references and MDN.

Solution 2:

You're right keys can only be strings, and numeric keys such as those used in Arrays are coerced and stored as strings.

var arr = [true];
arr[0] === true;
arr['0'] = false;
arr[0] === false;

ECMAScript spec, page 42: ECMA-262 Script 3rd Edition.

The production PropertyName : NumericLiteral is evaluated as follows:

  1. Form the value of the NumericLiteral.
  2. Return ToString(Result(1)).

Solution 3:

Well, here is my answer -- mostly because I was not satisfied with the references in the other (correct) answers -- expressions for property names in [ ] are always coereced to strings and this behavior is well defined in the specification. Thus, depending upon interpretation of the quote in question, it can be taken as misleading and/or incorrect.

However, the quote does not presume that x[42] and x["42"] are different; it states -- with the misleading exclusion of other primitives and details -- that only strings and numbers are usable as "hash keys" (really property names) under normal property resolution and, in this sense, the quote is arguably correct.

These rules are from Standard ECMA-262 ECMAScript Language Specification 5th edition (December 2009)

From section "11.2.1 Property Accessors" (production rules omitted):

The production MemberExpression : MemberExpression [ Expression ] is evaluated as follows:

  1. Let baseReference be the result of evaluating MemberExpression.
  2. Let baseValue be GetValue(baseReference).
  3. Let propertyNameReference be the result of evaluating Expression.
  4. Let propertyNameValue be GetValue(propertyNameReference).
  5. Call CheckObjectCoercible(baseValue).
  6. Let propertyNameString be ToString(propertyNameValue).
  7. If the syntactic production that is being evaluated is contained in strict mode code, let strict be true, else let strict be false.
  8. Return a value of type Reference whose base value is baseValue and whose referenced name is propertyNameString, and whose strict mode flag is strict.

Happy coding.

Solution 4:

The keys are always strings. This means you can't use an object instance's identity as a key.

In Flash's ActionScript 3 (uses strong run-time types unlike AS2) there is a Dictionary object which uses strict equality comparison for keys, so that you can use object instances themselves as keys (as well as numbers, strings, etc.).

If you wanted to do the same thing in JavaScript, it would be difficult, because you'd have to generate your own unique object ids and attach them to every object you wanted to track. Some have suggested adding a prototype function to the Object class, but that would add overhead to every object unnecessarily. In any case, you'd want to give an object a trackable ID via a function call that assigns an incrementing static number to a unique property such as "__objectid__".

It would then be conceivable to create a Dictionary-like class with methods like Add(key,value), but it would have to store strings, numbers, and objects in three separate internal hashes to ensure "3" doesn't collide with the number 3 or the object with id 3. The add method would have to automatically assigned an __objectid__ to any key of type object that didn't already have an id assigned. Even after all that, you wouldn't be able to access the dictionary using brackets, unless there are some hooks for property assignments that I'm not aware of in JavaScript.