6

What's a better practice, this:

myArray.forEach(function(item)) {

    doSomething(item);

    function doSomething(an_item) {
        console.log(an_item);   
    }

}

or this:

myArray.forEach(function(item)) {

    doSomething(item);

}

function doSomething(an_item) {
    console.log(an_item);   
}

Does the first example create multiple instances of the function, or does it create it just the first time through the loop?

Thanks for any insight!

dylanized
  • 3,765
  • 6
  • 32
  • 44

5 Answers5

4
myArray.forEach(function(item)) {

    doSomething(item);

}

function doSomething(an_item) {
    console.log(an_item);   
}

this function is best because it will created only one time ;

and

myArray.forEach(function(item)) {

    doSomething(item);

    function doSomething(an_item) {
        console.log(an_item);   
    }

}

is a bad due to every time function will create during loop process

Imran Ali Khan
  • 8,469
  • 16
  • 52
  • 77
2

The second. Use the second form (because the first form will slow down your user's experience, which may well be a phone or low powered device), or the even shorter form

myArray.forEach(doSomething);

function doSomething(element, index, array) {
  console.log("myArray[" + index + "] = " + element);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

It really depends on the interpreter if your asking a pure question about performance, i would imagine some of the smarter ones would be good enough to not create and destroy the function each time if they never change during the loop but realistically thats what your telling it to do (Create the function each time as the scope is temporary) so don't be surprised if thats the case. imagine if for example you were dynamically creating a closure within the forEach, wouldn't each loop need to create a new copy of the function?

http://jsperf.com/closure-vs-name-function-in-a-loop/2

certianly I would imagine older browsers not being smart enough to know to only make it once.

another post: Don't make functions within a loop

Community
  • 1
  • 1
Matt617
  • 458
  • 2
  • 14
2

I agree with what the others have said, and +1 on the second solution. You don't ever want to define/create functions within loops.

**Bonus

If you're function has to do with an object within the forloop, you can use this in your helper instead of passing the object via a parameter:

Example:

var myArray = [{ a: 1 }, { a: 2 }, { a: 3 }];

myArray.forEach(function(item) {
    doSomething.call(item);
});

function doSomething(item) {
    console.log(this.a);
}
ItsJonQ
  • 202
  • 3
  • 3
-4

It is good practice to always define things in the smallest scope possible.

So when you don't need the function elsewhere, defining it in the loop which uses it is the best choice.

Philipp
  • 67,764
  • 9
  • 118
  • 153