DEV Community

Discussion on: The Art of Refactoring: 5 tips to Write Better Code

Collapse
 
worsnupd profile image
Daniel Worsnup

Great article! An important thing to keep in mind when using objects as lookup tables is that objects have prototype chains that will also be checked if you are not careful. Look at this example, using some code from the article:

There are a few fixes for this:

  1. Create the object without a prototype (Object.create(null)):

    const pokemon = Object.assign(Object.create(null), {
        Water: 'Squirtle',
        Fire: 'Charmander',
        Plant: 'Bulbasur',
        Electric: 'Pikachu'
    });
    // pokemon.toString does not exist!
    
  2. Only check the object's "own" properties (hasOwnProperty)

    function getPokemon(type) {
      return pokemon.hasOwnProperty(type) ? pokemon[type] : 'Mew';
    }
    
  3. As you also suggested: Use a Map which inherently doesn't have this problem.

Thanks for the content!