r/learnjavascript • • May 15 '19

7 Useful JavaScript Tricks

https://davidwalsh.name/javascript-tricks
70 Upvotes

18 comments sorted by

View all comments

Show parent comments

1

u/delventhalz May 16 '19

As I said, I've used Object.create(null) for creating dictionary-like objects where the keys are user-supplied. E.g. something like a mime type in an archive format or a request header.

Okay. Cool. Seems like in the post ES6 era a Map is the better solution. Unless I am missing something?

In my experience, convenience (or "simplicity", an oft-abused term) should be third or fourth priority when writing code. First priority (after satisfying the AC), should be clarity. Imagine being a new developer on a project, calling an object method on what appeared to be an object, and then spending the better part of a day tracking the bizarre errors that resulted.

A Map is clear. hasOwnProperty is clear. My little hasProp one-liner? Clear. If a new developer does not understand how it works from context, they know to look up the function definition. Everything is perfectly transparent. Object.create(null) just seems like setting a booby trap for future developers.

1

u/inu-no-policemen May 16 '19

Seems like in the post ES6 era a Map is the better solution. Unless I am missing something?

Yes, Map<K, V> can store anything a dictionary-like object (<string, V>) can store. You certainly can use that instead.

However, it's a bit slower and you can't use [] or []= (like you can with Dart's Maps, for example).

hasOwnProperty is clear.

But it wouldn't work. It also isn't obvious that it won't. That should be pretty high on your list, right?

Object.create(null) just seems like setting a booby trap for future developers.

This is one of the two ways to use Object.create. It isn't anything special. A JS developer should roughly know how prototypes work. This crap is a very important detail of this language.