Last Updated: February 25, 2016
·
390
· konstantin

Alternative switch

Sometimes you come across the situation where you want to set some variable value based on the other variable, that can actually take many different values. Say, you have a variable "some" that can take values 1, 2, 3 and you want to set value for variable "o" based on value of variable "some". You can do a switch statement, if blocks or ternary operators. But there is another way. You can make an object with value of "some", values for "o":

var some = 1,
       o = {"1": "value1", "2": "value2", "3": "value3"}[some]

Same thing if you wanna perform some action based on value of "some":

var some = "a",
       a = function() {console.log("a")}, 
       b = function() {console.log("b")}, 
       c = function() {console.log("c")}; 

    ({
      "a": a, 
      "b": b, 
      "c": c
    }[some]())

So what about default value, when "some" is neither 1, 2 nor 3. The code can be rewritten as anonymous function that will verify whether attribute exists or not:

var some = 4, 
       o = (function () { 
               var opts = {
                   "1": "value1", 
                   "2": "value2", 
                   "3": "value3"
               };

               return (
                   typeof(opts[some])!=='undefined'?
                       opts[some]:
                       "default"
               )
           }())

Which looks nasty =)