3

Say I have a Javascript array which contains numbers between 0 and 5. Each of the numbers is really an instruction to call a specific function. For example:

var array = [lots of data];

for(i=0; i<array.length; i++){
  if(i == 0){ function0(); };
  if(i == 1){ function1(); };
  if(i == 2){ function2(); };
  if(i == 3){ function3(); };
  if(i == 4){ function4(); };
  if(i == 5){ function5(); };
}

This seems like an awful lot of branching and unnecessary checks. What would be a more performance minded way to call the function?

I've thought about dynamically creating the function names using eval, but isn't there a better way?

YAHsaves
  • 1,697
  • 12
  • 33

3 Answers3

3

Store the functions in the array;

var array = [function0, function1, ..., functionN];

and then just call the functions on each iteration:

for (var i=0; i<array.length; i++) {
  array[i]();
}
ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
  • Awesome thank you I think the answer is the simplest most readable way to go! I knew there was an obvious easy way I just overlooked – YAHsaves Jun 01 '18 at 01:58
2

Use an Object as a map, or use the switch statement. The former is demonstrated below.

const functionMap = {
    0: function0,
    1: function1,
    2: function2
};

array.foreach(i => functionMap[i]());

Alternatively, if you can know the name of the function based off of i, you can call it from the parent scope, e.g.

window[`function${i}`]()

However, strictly speaking, manually coding in the if statements (or using a switch) may be the most performant. I doubt there will be a significant performance difference between any of them.

Jared Goguen
  • 8,772
  • 2
  • 18
  • 36
  • 1
    .foreach() would be more appropriate than .map() here – Jye Lewis Jun 01 '18 at 01:49
  • The 2 options you posted are great examples how I've overlooked the most simple of things! I looked up how switch works on the backend, and it's similar to if-than, however the functionMap makes a type of dictionary Hash table to compare id's to keys, making it significantly faster. However after reading all the answers I think the fastest way is to store the function in an array and access the index. – YAHsaves Jun 01 '18 at 02:05
1

Functions can be called as strings, so window['function' + i]() would work, and call a function. This can be very dynamic.

var array = [0, 1, 2];

function function0() { console.log('Function 0') }
function function1() { console.log('Function 1') }
function function2() { console.log('Function 2') }

for (i = 0; i < array.length; i++) {
  if (typeof window['function' + i] == 'function') {
    window['function' + i]()
  }
}
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • Doing this is generally not good practice, accessing global variables by string keys is difficult to track / debug & the usage of each function is not as immediately obvious. – Jye Lewis Jun 01 '18 at 04:43