JavaScript For Loop How does it work?

What does this code mean?

for (var i = 5; i < 51; i++) {
console.log(i);
}

for_loop

Imagine a musical metronome with a big arm swinging left and right.

Imagine that each time the arm clicks left, right, left, you say out loud 5, then 6, then 7, etc.

Ok, in the script above, the ticking of the metronome is a temporary variable called i.

You are JavaScript. And your voice out loud is console.log( ).

The script above takes an arbitrarily named variable, i that keeps pointing at numbers, starting at 5 and stopping at 50 (inclusively). That’s the ticktock of the metronome.

JavaScript guides itself by the “sound” of i, and it performs the command inside of the body of the loop which is to display out loud “5”, “6”, “7”… “50”. On 50 i stops counting and JavaScript knows it is time to exit the loop.

Console.log() prints out each number at each position of i.
i++ is a shortcut that means “increment by 1”, which happens once on each cycle of the loop.

for i starting at 5, i less than 50, increment i
while incrementing, print each time, the value "at" i
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