Some languages implement hash tables which can use anything, not just strings, as a key. In JavaScript, you are restricted to strings and numbers. Is the lookup for this kind of implementation still O(1)? Is there an implementation in JavaScript?
Some languages implement hash tables which can use anything, not just strings, as a
Share
There’s obviously a lot of misunderstanding around this subject. In JavaScript, they keys of objects are actually only strings (see §8.10). Anything (including numbers) used as an object key is converted to string. Thus,
obj[1]andobj["1"]are equivalent.Internally, many JS implementations use some kind of hash table to enable quick lookup of object properties. V8 actually generates hidden C++ classes that allows lookups to execute in a single CPU instruction. Either way, it’s safe to assume that object property access is fast and near O(1).
As a consequence of all object property keys being converted to string, you can only use things that convert to string as a key. Since numbers naturally convert to string, they work fine. Same for booleans. Dates work too, since
Dateinstances convert to unique strings (although there are edge cases to be aware of).However, objects do not convert into meaningful strings. For example:
Actually results in:
because of the string conversion rules. Since every object converts to
[object Object], adding many objects as keys to another object will result in an object with only one property.Of course, it’s still possible to use an object as a key. You just have to override the default implementation of
toString— in effect, creating your own hashing algorithm. For example,Results in: