For Loop Syntax?


#1

In a for loop I've been using this format and it's been taking it:

for (i = 0; i < 10; i++){

}

but in a later exercise, after taking it, it changed it to:

for (var i = 0; i < 10; i++){

}

Do I need to specify that i is a variable or is JavaScript smart enough to know that it's a temporary variable for the for loop since it's in a for loop?


#2

Do I need to specify that i is a variable or is JavaScript smart enough to know that it's a temporary variable for the for loop since it's in a for loop?

When you ommit the var JavaScript will create a global variable (if this variable is not already defined), difference:

for (i = 0; i < 10; i++){
    // do something
}

console.log(i);
// => 10

And the same code with var:

for (var i = 0; i < 10; i++){
    // do something
}

console.log(i);
// => undefined

What is the advantage of using var in the for loop? As you already said, we want to create a temporary variable. It does not make any sense to keep this variable in memory or to pollute the global namespace. Use var.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.