3

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?

Boris Šuška
  • 1,796
  • 20
  • 32
  • 1
    http://es5.github.io/x12.html#x12.6.3 – Kijewski Aug 10 '14 at 22:55
  • That is correct, you declare the variable before the while loop, not inside it. – adeneo Aug 10 '14 at 22:55
  • what are you talking about "the worst notation is declare i variable in the beggining of function body". I'm pretty sure javascript hoists all variables to the beginning of the function body – Scott Mitchell Aug 10 '14 at 23:03
  • Forget the "JavaScript hoists variables" part, it is a beginners mistake. I think a gave a proper/brief overview in http://stackoverflow.com/a/10792121/. – Kijewski Aug 10 '14 at 23:06
  • Im confused on what you are saying. You are saying that javascript does NOT hoist variables to the top of the scope? Just would like to confirm – Scott Mitchell Aug 10 '14 at 23:10
  • @ScottMitchell I mean it is the worst notation when I'm doing it manually, if interpretter is doing so I don't care. For a loops it is not nice to have `var i;` lot of lines of code and finally few lines with `i` variable. – Boris Šuška Aug 10 '14 at 23:15

1 Answers1

5

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
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143