Using var keyword during loop definition
In JavaScript, for a loop, I can use a keyword var
in the loop definition something like this:
for (var i=0; i<10; i++) ...
I know that the scope of a variable i
is not inside the loop, but inside the function where the loop is declared. This is better than declaring a local variable i
outside of the loop (the worst notation is to declare a variable i
at the beginning of the function body):
var i;
for (i=0; i<10; i++) ...
My question is about a while loop. I cannot declare a variable in a loop definition like this:
while((var match = re.exec(pattern)) != null) ...
I need to use the keyword var
outside of the while loop.
var match;
while((match = re.exec(pattern)) != null) ...
Am I doing something wrong?
source to share
Am I doing something wrong?
No no. This is how the syntax is defined. A loop while
only accepts an expression, and a loop for
can also be used with a declaration var
.
See https://es5.github.io/#x12.6 :
while ( Expression ) Statement
for ( ExpressionNoIn_opt; Expression_opt ; Expression_opt ) Statement
for ( var VariableDeclarationListNoIn; Expression_opt ; Expression_opt ) Statement
source to share