Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficent way to code branches in Javascript

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?

like image 822
YAHsaves Avatar asked Feb 26 '26 19:02

YAHsaves


1 Answers

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]();
}
like image 145
ic3b3rg Avatar answered Feb 28 '26 09:02

ic3b3rg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!