views:

33

answers:

5

Hello stackoverflow!

I have a certain loop occurring several times in various functions in my code. To illustrate with an example, it's pretty much along the lines of the following:

for (var i=0;i<= 5; i++) {
    function1(function2(arr[i],i),$('div'+i));
    $('span'+i).value = function3(arr[i]);
}

Where i is the loop counter of course. For the sake of reducing my code size and avoid repeating the loop declaration, I thought I should replace it with the following:

function loop(s) {
 for (var i=0;i<= 5; i++) { eval(s); }
}

[...]

loop("function1(function2(arr[i],i),$('div'+i));$('span'+i).value = function3(arr[i]);");

Or should I? I've heard a lot about eval() slowing code execution and I'd like it to work as fast as a proper loop even in the Nintendo DSi browser, but I'd also like to cut down on code. What would you suggest?

Thank you in advance!

+4  A: 

Why not just put the body of the loop into a function?

function doSomething(i, arr) {
    function1(function2(arr[i],i), $('div'+i));
    $('span'+i).value = function3(arr[i]);
}

and call it in the loop:

function loop() {
    for (var i = 0; i <= 5; i++) { doSomething(i, arr); }
}
Darin Dimitrov
A: 

This is a dreadful idea.

  • It is inefficient
  • It is harder to debug

If you are concerned about bandwidth then use minification and HTTP compression.

David Dorward
+1  A: 

Gah!

This is a good question, but no, don't ever do that. Using eval in general is not recommended, as you won't see parse errors at load time, only at run time (harder to debug), it's harder to understand what's in scope when (harder to write), and you lose all your toolchain support (syntax highlight, script debugging).

Fortunately, since Javascript is basically a functional language, why not create a function that encapsulates what you want to do, and just call that?

function doMyThingNTimes(n, arr) {
    for (var i=0;i <= n; i++) {
        function1(function2(arr[i],i),$('div'+i));
        $('span'+i).value = function3(arr[i]);
    }
}
quixoto
No no, that wouldn't work, because the first bit of code is as I said an example, it changes of course, it's not just those two lines
Herc
OK, so put whatever it is you need in a helper function-- that's what functions are for, and that's how you build software. :)
quixoto
A: 

Uh, no. eval should be treated as close to a last resort. JavaScript functions are First Class Objects so I would just declare whatever functions you need and pass them as one of the params.

Peter Rowell
A: 

Why not:

function loop(s) {
  for (var i=0;i<= 5; i++) { s(i); }
}

loop(function4() {
    function1(function2(arr[i],i),$('div'+i));$('span'+i).value = function3(arr[i]);
});
RichN
Hm, hadn't thought of that one, not much of an improvement sizewise though :/
Herc