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?

6
  • 1
    es5.github.io/x12.html#x12.6.3 Commented Aug 10, 2014 at 22:55
  • That is correct, you declare the variable before the while loop, not inside it. Commented Aug 10, 2014 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 Commented Aug 10, 2014 at 23:03
  • Forget the "JavaScript hoists variables" part, it is a beginners mistake. I think a gave a proper/brief overview in stackoverflow.com/a/10792121. Commented Aug 10, 2014 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 Commented Aug 10, 2014 at 23:10

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.