Rewriting switch statements to lookup objects

Some switch-statements can be replaced with lookup-tables in JavaScript. If every case immediately returns a value, this pattern achieves the same in fewer lines of code.

// before: switching through the values to return a number requires a lot of code
const getFeetForAnimal = animal => {
  switch (animal) {
    case 'bird':
      return 2
    case 'dog':
      return 4
    case 'fish':
      return 0
    case 'spider':
      return 8
  }
}

// after: a lookup object and implicit `return` do the same in fewer lines
const getFeetForAnimal = animal => ({
  bird: 2,
  dog: 4,
  fish: 0,
  spider: 8
})[animal]

getFeetForAnimal('dog')     // ⇒ 4
getFeetForAnimal('gorilla') // ⇒ undefined (does not exist in lookup table)

There is more to learn

Get free previews of my upcoming course materials and other bonus content to help you work smarter. I share tips straight to your inbox once a week. You can read previous mails in the newsletter archive.

Cannot show form because cookie consent was not given.