Reputation: 10624
I believed the variable should be out of the loop, so that define variable only once.
Like,
var target;
elementsArray.forEach(function(ele) {
target = $('input[name=' + ele + ']');
// do something with target
});
but, I read some JS coding recommendation, that said, the variable should be defined in the scope.
then should I use like this? ,
elementsArray.forEach(function(ele) {
var target = $('input[name=' + ele + ']');
// do something with target
});
It doesn't cost any if creating multiple new instance?
Upvotes: 2
Views: 66
Reputation: 68443
It is not just a loop, it is function being called inside a loop.
And each function has its own scope.
In the first example, target is visible to function enclosing this forEach loop, in the second example, target is only visible inside this function.
Upvotes: 0
Reputation: 36609
Both the
foreach
will behave differently.forEach
creates newscope
(function level) for each item in array..
For global variable, it will override the value for each iteration..for local, it will create new instance for each item.
If there are any click events
are being handled in forEach
, for global
variable, it will always take last item into consideration as value is overwritten.
Upvotes: 0
Reputation: 128856
It only really matters if you're doing something with it outside of the loop.
target
outside of the loop will mean that after your loop has executed the last $('input[name=' + ele + ']')
element hit by your loop will still be assigned to your target
variable.target
inside of the loop will mean that target
will be undefined outside of the loop.Upvotes: 1