Essential
Essential

Reputation: 421

use existing variable in for loop

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
}

Upvotes: 9

Views: 8189

Answers (3)

Sampson
Sampson

Reputation: 268344

You can count down from any arbitrary number:

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

Which outputs: 2, 1, 0

Upvotes: 0

jahroy
jahroy

Reputation: 22692

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

var otherVar = 3;

for ( ; otherVar > 0; otherVar-- ) {
    doStuff();
}

Upvotes: 16

J A
J A

Reputation: 1766

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

otherVar = 3;

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

Upvotes: 1

Related Questions