marijnh / Eloquent-JavaScript

The sources for the Eloquent JavaScript book
https://eloquentjavascript.net
3.01k stars 795 forks source link

Ch. 6 – Maps clarification #363

Closed mikegowen closed 6 years ago

mikegowen commented 6 years ago

The paragraphs below had me scratching my head a bit. I'll propose a minor clarification...

As such, using plain objects as maps is dangerous. There are several possible ways to avoid this problem. Firstly, it is possible to create objects with no prototype. If you pass null to Object.create, the resulting object will not derive from Object.prototype, and can safely be used as a map.

console.log("toString" in Object.create(null)); // → false

However, because property names are strings, this still doesn’t help when your key values are of some other type.

to

Using plain objects as maps is dangerous, as you may inadvertently add property names that collide with existing property names in the object's prototype. One way to avoid this is to create objects with no prototype. If you pass null to Object.create, the resulting object will not derive from Object.prototype, and can safely be used as a map.

console.log("toString" in Object.create(null)); // → false

Also, object property names must be strings or symbols (more on symbols later). If you'd like to use something other than a string or symbol for a property name (such as a number, function, object, etc.) using a plain object as a map will not work.

You get the idea. May need some wordsmithing.

Also, you'd want to adjust this paragraph for obvious reasons, if you went with the above proposed changes: http://eloquentjavascript.net/3rd_edition/06_object.html#p_7p+O+Qr4bN

marijnh commented 6 years ago

as you may inadvertently add property names that collide with existing property names in the object's prototype

That's not the problem — the problem is described in the preceding paragraph, namely that in will tell you your object has properties that are actually in Object.prototype.

The second paragraph could be clearer. I've simplified it in attached patch.