Rewriting Javascript : Replacing the Switch Statement

Chris Burgin
Apr 17, 2017 · 4 min read
TLDR; See Banner Image.

The Problem

const dogSwitch = (breed) => {
  switch(breed) {
    case("border"):
      return "Border Collies are good boys and girls."
      break;
     case("pitbull"):
      return "Pit Bulls are good boys and girls."
      break;
     case("german"):
      return "German Shepherds are good boys and girls."
      break;
  }
}dogSwitch("border") // "Border Collies are good boys and girls."

1. Non Standard Syntax

// returns `hi {name}`
const sayHi = (name) => 
  `Hi ${name}!!`sayHi("Chris") // output: Hi Chris!

2. Error Prone

switch("first") {
  case("first"):
    console.log("First Case")
  default:
    console.log("Default Case")
}

The Solution

const dogSwitch = (breed) => ({
  "border": "Border Collies are good boys and girls.",
  "pitbull": "Pit Bulls are good boys and girls.",
  "german": "German Shepherds are good boys and girls."
})[breed]dogSwitch("border") // "Border Collies are good boys and girls."
const jsonObject = {
  "i1": "item 1",
  "i2": "item 2"
}jsonObject["i1"] // "Item 1

A Complex Example

Redux Store Reducers with Object Literals

Conclusion

Thanks! 💚

Useful Reading

Spark

Welcome to Spark! A publication centered around web development and design.

Chris Burgin

Written by

Christ follower. Dog caretaker. Developer at Generation Tux.

Spark

Spark

Welcome to Spark! A publication centered around web development and design.