How Does a JavaScript ‘for’ Loop Work?

How to Use a ‘for’ Loop in Javascript 🙂

Image for post

A ‘for’ loop includes three statements in parentheses, the initialization, the condition, and the check.

Let’s take a look at the structure of a simple ‘for’ loop:

for (var i = 0; i <= 19; i++) {

The three statements in parentheses: The Initialization, The Condition, and The Change.

The Initialization: var i = 0;

The initialization is where a variable is set or declared and set to be a certain value. Here we declare the variable with ‘var i’, since the variable ‘i’ does not yet exist, but we could also use an exisiting variable and would then not have to declare it in the first statement.

This variable is used within the code of the ‘for’ loop, as well as being the first statement of the ‘for’ loop in parentheses. We’ll call this variable the loop’s variable. A single letter is usually used for this variable, as it is only used for the purposes of it’s particular loop, and doesn’t exist outside the loop. The letters ‘i’, ‘j’, and ‘k’ are commonly used.

The Condition: i <= 19;

The condition is checked each time the loop runs, and once it is no longer met, the loop stops running. The condition includes the variable that was used for initialization.

The Change: i++

The third statement in a ‘for’ loop is the change. The change of a ‘for’ loop alters the value of the loop’s variable.


The Logical Flow of This ‘for’ Loop:

Our ‘for’ loop runs like this:

First the varible ‘i’ is set to 0.

Next the value of ‘i’ is printed to the console, from the line console.log(i);

Next, ‘i’ has a value of 1 added to it, from the change statement in the ‘for’ loop.

After that, the condition statement is checked, to see if ‘i’ still meets the condition. Since 1 is less than 19, the loop runs again, and prints ‘1’ to the console.

This continues until the i = 20, and the loop exits.

The control flow looks something like this:

Image for post

And there you have it! Now you know how a ‘for’ loop works. =)