Last Updated: February 25, 2016
·
4.063K
· 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.