Expert wanna be
Expert wanna be

Reputation: 10624

define variable in loop scope or should be out of scope?

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

Answers (3)

gurvinder372
gurvinder372

Reputation: 68443

Both are not the same things

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

Rayon
Rayon

Reputation: 36609

Both the foreach will behave differently. forEach creates new scope(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

James Donnelly
James Donnelly

Reputation: 128856

It only really matters if you're doing something with it outside of the loop.

  1. Defining 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.
  2. Defining target inside of the loop will mean that target will be undefined outside of the loop.

Upvotes: 1

Related Questions