JSlint error 'Don't make functions within a loop.' leads to question about Javascript itself

javascript, jslint

Solution

Would a Javascript interpreter really create an instance of the function per iteration?

It has to because it doesn't know if the function object will be modified elsewhere. Remember that functions are standard JavaScript objects, so they can have properties like any other object. When you do this:

card = $('<div>').bind('isPopulated', function (ev) { ... })

for all you know, `bind` could modify the object, for example:

function bind(str, fn) {
  fn.foo = str;
}

Clearly this would result in wrong behaviour if the function object was shared across all iterations.

Problem

I have some code that invokes anonymous functions within a loop, something like this pseudo example: ``` for (i = 0; i < numCards; i = i + 1) { card = $('<div>').bind('isPopulated', function (ev) { var card = $(ev.currentTarget); .... ``` JSLint reports the error 'Don't make functions within a loop.' I like to keep my code JSLint clean. I know I can move the anonymous function out of the loop and invoke it as a named function. That aside, here's my question: Would a Javascript interpreter really create an instance of the function per iteration? Or is there really only one function instance "compiled" and the same code is executed repeatedly? That is, does the JSLint "suggestion" to move the function out of the loop actually affect the efficiency of the code?

Original source