Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using var keyword in while loop definition

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?

like image 984
Boris Šuška Avatar asked Aug 06 '26 17:08

Boris Šuška


1 Answers

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
like image 194
Felix Kling Avatar answered Aug 08 '26 10:08

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!