A counter for a for loop in JavaScript is not essential

Did you know that a conditional expression controlling a FOR LOOP does not have to be a counter?
That’s right, all it needs to be is a Boolean expression of any kind.
Take the following loop as an example:

var finish = true;

for (var i = 0; finish === true; i++) {

    if (i >= 5) {
        finish = false;
    }

    console.log(i);
}

// result: 0,1,2,3,4,5

Variable finish is originally true and as long as it is true the for loop will run just like a while loop would.
Then we can control the loop at any time by switching the value of finish to false as it was done by the conditional statement.

READ MORE HERE: http://bit.ly/1BWiSEI

Advertisements

Author: tarau

technical writer, web technologies

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s