Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript best practices - where's the best place to define a helper function inside a loop? [closed]

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!

like image 928
dylanized Avatar asked Jan 03 '14 03:01

dylanized


2 Answers

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

like image 74
Imran Ali Khan Avatar answered Sep 30 '22 19:09

Imran Ali Khan


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);
}
like image 23
Elliott Frisch Avatar answered Sep 30 '22 20:09

Elliott Frisch