O'Reilly logo

Practical Modern JavaScript by Nicolas Bevacqua

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 5. Leveraging ECMAScript Collections

JavaScript data structures are flexible enough that we’re able to turn any object into a hash-map, where we map string keys to arbitrary values. For example, one might use an object to map npm package names to their metadata, as shown next.

const registry = {}
function set(name, meta) {
  registry[name] = meta
}
function get(name) {
  return registry[name]
}
set('contra', { description: 'Asynchronous flow control' })
set('dragula', { description: 'Drag and drop' })
set('woofmark', { description: 'Markdown and WYSIWYG editor' })

There are several problems with this approach, outlined here:

  • Security issues where user-provided keys like __proto__, toString, or anything in Object.prototype break expectations and make interaction with this kind of hash-map data structures more cumbersome

  • When iterating using for..in we need to rely on Object#hasOwnProperty to make sure properties aren’t inherited

  • Iteration over list items with Object.keys(registry).forEach is also verbose

  • Keys are limited to strings, making it hard to create hash-maps where you’d like to index values by DOM elements or other nonstring references

The first problem could be fixed using a prefix, and being careful to always get or set values in the hash-map through functions that add those prefixes, to avoid mistakes.

const registry = {}
function set(name, meta) {
  registry['pkg:' + name] = meta
}
function get(name) {
  return registry['pkg:' + name]
}

An alternative could ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required