6e7rea
Last Updated: December 08, 2016
·
23.55K
· Stereobit
26bf316adf9d6df49b6d697ca0f31d37

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).

Say Thanks
Respond

5 Responses
Add your response

11786
0 ffbqyoyigrpdwu sbd3jywyehzojiugslwpjywmr0podq0zdwdberdvza4e6eyit625zlarug sr

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

over 1 year ago ·
11791
26bf316adf9d6df49b6d697ca0f31d37

You could use something like require js.

over 1 year ago ·
26341
None

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 ·
28198

@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 ·
28369

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

12 months ago ·