In JavaScript for loop I can use var keyword in loop definition something like that:
for (var i=0; i<10; i++) ...
I know scope of the variable i is not inside the loop but inside function where loop is declared. This it a better notation than declaring local variable i outside of the loop (the worst notation is declare i variable in the beggining of function body):
var i;
for (i=0; i<10; i++) ...
My question is about while loop. I'm not able declare variable in while loop definition something like this:
while((var match = re.exec(pattern)) != null) ...
I have to use var keyword outside of the while loop.
var match;
while((match = re.exec(pattern)) != null) ...
Am I doing something wrong?
Am I doing something wrong?
No you are not. That's just how the syntax is defined. The while loop only accepts an expression, while the for loop can also be used with a var declaration.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With