Search code examples
javascriptperformancecoding-style

Execute different functions based on conditions without if statements


Is there a better approach/coding style to execute different functions under different conditions without using if statements?

I have been coding in the following way in JavaScript: (for example, a function in different conditions might use different fetch methods from an API)

if(answer == 'a'){
  foo()

if(answer == 'b'){
  bar()

if(answer == 'c'){
  bar_2()

if(answer == 'd'){
  foo_3()

I have thought of using eval(), but is it a good approach? for example, creating an object consists of keys as conditions and function names as property.

conditions:{
  a: 'foo',
  b: 'bar',
  c: 'foo_2',
  d: 'bar_2',
}

and run it like eval(this.conditions[a])

But I also heard that using eval would be difficult for testing.


Solution

  • Yes, you can build your conditions object with the function and call them:

    function foo(){...}
    function bar(){...}
    
    var conditions : {
        'a': foo,
        'b': bar,
    }
    
    conditions[answer]()
    

    Note: try not to use eval whenever is possible it has security risks if you don't know what are you doing