9

Is it possible to leave out the variable assignment from a for loop and do something like this…?

otherVar = 3;

for ( otherVar > 0; otherVar-- )
{
    stuff
}
1
  • 1
    You can also declare a bunch of vars right in the loop: for(var someVar=0, otherVar=3, yetAnother='bob';yetAnother!==false;someVar++) Commented May 23, 2012 at 3:42

3 Answers 3

16

Yes, but you need to put in the semi-colon:

var otherVar = 3;

for ( ; otherVar > 0; otherVar-- ) {
    doStuff();
}
Sign up to request clarification or add additional context in comments.

Comments

1

Usually While is more popular for this situation (better readability)..

otherVar = 3;

while ( otherVar > 0)
{
   stuff
   otherVar--;
}

2 Comments

Ah, decided to do it your way. Not sure why I was trying to use a for loop. :)
Happy to help:). shorthand for the while condition is while( otherVar-- > 0 ) in case if don't like to use incrementation at the end of the loop. Btw, +1 is a good way to mention that the answer was useful here in SO. Thanks
0

You can count down from any arbitrary number:

var counter = 3;
while ( counter-- ) {
  console.log( counter );
}

Which outputs: 2, 1, 0

1 Comment

Just a quick question. Correct me if I'm wrong but the while loop runs till the expression inside the parentheses is true right. when does counter-- become false or true.

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.