Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using anonymous function in javascript for loops

I have seen anonymous functions inside for loops to induce new scope on the web in one or two places and would like to know if it makes sense.

for example:

var attr, colors = ['green','blue','red'];

for ( attr = 0; attr < colors.length; attr++) {
    (function() {
        var colorAttr = colors[attr];

        // do something with colorAttr
    })();
}

I understand it has something to do with keeping the scope inside the for loop clean, but in what situations would this be necessary? Would it be good practice to do this everywhere you need to declare a new var inside the for loop?

like image 483
Evan Avatar asked Dec 20 '12 17:12

Evan


People also ask

How do I run an anonymous function in JavaScript?

Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.

What are anonymous functions in JavaScript used for?

Anonymous functions are functions without names. Anonymous functions can be used as an argument to other functions or as an immediately invoked function execution.

When would you use an anonymous function?

Anonymous functions are often arguments being passed to higher-order functions, or used for constructing the result of a higher-order function that needs to return a function. If the function is only used once, or a limited number of times, an anonymous function may be syntactically lighter than using a named function.

Can you use an anonymous function in a callback?

In JavaScript, callbacks and anonymous functions can be used interchangeably.


1 Answers

2021 Update

var used to be the only way to declare a variable. But we now have const and let which solve this problem in a better way. These variable declarations do respect the loop as a scope to bind to, which means the following snippet works fine and there is no need for an anonymous function to capture those values.

const colors = ['green', 'blue', 'red'];

for (let i = 0; i < colors.length; i++) {
    const color = colors[i];
    setTimeout(function() {
        alert(color);
    }, i * 1000);
}

What follows below is my original answer to this question from 2012.


When you have inner functions that are not executed immediately, as part of the loop.

var i, colors = ['green', 'blue', 'red'];

for (i = 0; i < colors.length; i++) {
    var color = colors[i];
    setTimeout(function() {
        alert(color);
    }, i * 1000);
}

// red
// red
// red

Even though var color is inside the loop, loops have no scope. You actually only have one variable that every loop iteration uses. So when the timeouts fire, they all use the same value, the last value set by the loop.

var i, colors = ['green', 'blue', 'red'];

for (i = 0; i < colors.length; i++) {
    (function(color) {
        setTimeout(function() {
            alert(color);
        }, i * 1000);
    })(colors[i]);
}

// green
// blue
// red

This one captures the value at each iteration into an argument to a function, which does create a scope. Now each function gets it's own version of a color variable which won't change when functions created within that loop are later executed.

like image 153
Alex Wayne Avatar answered Nov 22 '22 11:11

Alex Wayne