Last Updated: February 25, 2016
·
4.708K
· jonotron

Use dictionary lookups instead of switch statements

Switch statements are fun and all, but they can be awkward to write and read:

function getTemplateForState(state) {
  switch (state) {
    case 'edit':
      return myEditTemplate;
    case 'add':
      return myAddTemplate;
    case 'item':
      return myItemTemplate;
  }
}

Instead, consider doing a dictionary lookup in an object hash:

var templates = {
  'edit': myEditTemplate,
  'add': myAddTemplate,
  'item': myItemTemplate
}

function getTemplateForState(state) {
  return templates[state];
}

This is easier to read and maintain.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside