Last Updated: December 08, 2016
·
38.98K
· Stereobit

Consider lookup tables instead of switch or if/else

There are a couple of methods to make distinctions between different possibilities. You can use if-else clauses:

function ifElseTest(stuff) {
  if(stuff === "pizza") {
    return "food";
  } else if (stuff === "house") {
    return "building";
  } else if (stuff === "air") {
    return "nothing";
  }
};

Or switch:

function switchTest(stuff) {
  switch (stuff) {
    case "pizza":
      return "food";
    break;

    case "house":
      return "building";
    break;

    case "air":
      return "nothing";
    break;
  }
};

But there is a possible faster one (http://jsperf.com/if-switch-lookup-table/1) – a simple lookup table in the form of an object:

var lookupTable = {
  "pizza": function() {
    return "food";
  },
  "house": function() {
    return "building";
  },
  "air":  function() {
    return "nothing";
  }
};

just call

lookupTable["condition"]()

to choose your wished conclusion.

Update:
For sure you should use this technique carefully. It's not always the best solution. Especially when you deal with integer conditions instead of strings (see http://coderwall.com/p/doeskg).

5 Responses
Add your response

Is there a simple way of initializing the lookup table from an external file?

over 1 year ago ·

You could use something like require js.

over 1 year ago ·

Hi there,

1) Why are you using functions in the looking table.
Why not

var lookupTable = {

"pizza": "food",

"house": "building",

"air": "nothing",

};

console.log(lookupTable[condition]);

???

2) No default value in your examples.
In real life you'll have one generally. In this case, the lookup table is less efficient because you have to test the return value.

over 1 year ago ·

@Polatouche The function does not have to be returning a string. This is just an example. The function could be as complex as you like.

over 1 year ago ·

In the case of integer conditions, particularly consecutive, you could just use a lookup array.

over 1 year ago ·