Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"var" or no "var" in JavaScript's "for-in" loop?

What's the correct way to write a for-in loop in JavaScript? The browser doesn't issue a complaint about either of the two approaches I show here. First, there is this approach where the iteration variable x is explicitly declared:

for (var x in set) {
    ...
}

And alternatively this approach which reads more naturally but doesn't seem correct to me:

for (x in set) {
    ...
}
like image 330
futlib Avatar asked Apr 19 '11 13:04

futlib


People also ask

Why VAR is not used in for loop in JavaScript?

Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with let are local to the statement.

Do you need a variable for a for loop?

A for loop is like a function in that they are both used to execute the SAME code multiple times on DIFFERENT things. You need variables to stand in for the different things.

Is it necessary to write VAR in JavaScript?

Always declare JavaScript variables with var , let , or const . The var keyword is used in all JavaScript code from 1995 to 2015. The let and const keywords were added to JavaScript in 2015. If you want your code to run in older browsers, you must use var .

Is VAR optional in JavaScript?

Variables can be declared and initialize without the var keyword. However, a value must be assigned to a variable declared without the var keyword. The variables declared without the var keyword becomes global variables, irrespective of where they are declared. Visit Variable Scope in JavaScript to learn about it.


3 Answers

Use var, it reduces the scope of the variable otherwise the variable looks up to the nearest closure searching for a var statement. If it cannot find a var then it is global (if you are in a strict mode, using strict, global variables throw an error). This can lead to problems like the following.

function f (){
    for (i=0; i<5; i++);
}
var i = 2;
f ();
alert (i); //i == 5. i should be 2

If you write var i in the for loop the alert shows 2.

JavaScript Scoping and Hoisting

like image 163
Gabriel Llamas Avatar answered Oct 18 '22 03:10

Gabriel Llamas


The first version:

for (var x in set) {
    ...
}

declares a local variable called x. The second version:

for (x in set) {
    ...
}

does not.

If x is already a local variable (i.e. you have a var x; or var x = ...; somewhere earlier in your current scope (i.e. the current function)) then they will be equivalent. If x is not already a local variable, then using the second will implicitly declare a global variable x. Consider this code:

var obj1 = {hey: 10, there: 15};
var obj2 = {heli: 99, copter: 10};
function loop1() {
    for (x in obj1) alert(x);
}
function loop2() {
    for (x in obj2) {
        loop1(); 
        alert(x);
    }
}
loop2();

you might expect this to alert hey, there, heli, hey, there, copter, but since the x is one and the same it will alert hey, there, there, hey, there, there. You don't want that! Use var x in your for loops.

To top it all off: if the for loop is in the global scope (i.e. not in a function), then the local scope (the scope x is declared in if you use var x) is the same as the global scope (the scope x is implicitly declared in if you use x without a var), so the two versions will be identical.

like image 44
Claudiu Avatar answered Oct 18 '22 03:10

Claudiu


You really should declare local variables with var, always.

You also should not use "for ... in" loops unless you're absolutely sure that that's what you want to do. For iterating through real arrays (which is pretty common), you should always use a loop with a numeric index:

for (var i = 0; i < array.length; ++i) {
  var element = array[i];
  // ...
}

Iterating through a plain array with "for ... in" can have unexpected consequences, because your loop may pick up attributes of the array besides the numerically indexed ones.

edit — here in 2015 it's also fine to use .forEach() to iterate through an array:

array.forEach(function(arrayElement, index, array) {
  // first parameter is an element of the array
  // second parameter is the index of the element in the array
  // third parameter is the array itself
  ...
});

The .forEach() method is present on the Array prototype from IE9 forward.

like image 25
Pointy Avatar answered Oct 18 '22 02:10

Pointy