How to Use for Statements in JavaScript

  • 5 min read
  • December 2, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

A for loop will repeatedly execute a function or a code block until a provided condition evaluates to false.

 

Basic for loop example

Let’s begin with an easy example – printing the numbers 1 to 10 to the console.

While it is possible to write ten different console.log() statements, each with a different value to be printed, this approach quickly becomes challenging to maintain. What if we wanted to expand the print commands to include the numbers 1 to 100? Or 1,000? It is far more efficient to use the for statement, as seen in the example below:

for (let i = 1; i <= 10; i++) {
    console.log(i);
}

The code example above results in printing the numbers 1 through 10 to the console, in a much more compact fashion than if each console.log() statement was written individually.

Syntax

The syntax for for statements is as follows:

for ( initialState; condition; stateUpdate ) {

function or code block for execution

}

initialState: creates the counter variable and assigns the initial value that the loop will begin with.

condition: sets the condition for loop completion.

stateUpdate: defines how to update the counter variable after each loop iteration.

All three expressions above are optional. However, if you choose to skip one, you must not omit the semicolons!

The code above declares the counter variable using let i, and assigns it the value of 1 (thus setting the initialState). As long as i is less than or equal to ten (condition: i <= 10 ), execution of the code block will continue. The variable i is incremented by 1 after each execution of the code block (stateUpdate: i++ ).

In each loop iteration, i‘s value is different. Its value starts at 1, and is incremented by 1 after each execution of the code block. When i evaluates to 11, it no longer satisfies the condition (i <= 10), which causes the loop to end.

Note: an invalid stateUpdate or condition may result in an infinite loop! In this case the code block will run repeatedly until the code execution is interrupted by external means.

for statement expressions

Below are some additional details on each of the elements of the for statement.

intialState

The initialState element can include several values. Each value must be separated by a comma, as seen below:

for (let i = 0, x = 3; i < 3; i++) {
    console.log(i ** x);
}
// Expected output:
// 0
// 1
// 8

As seen above, the initialState defines two counter variables – i and x. These can then be used in the loop’s code block.

Omitting the initialState expression

You do not always need to specify an initialState expression. For example, if you had two variables that were created outside of the for loop, you can use those to control the behavior of the loop by simply omitting the initialState expression. The following example demonstrates this concept by defining the variables i and x outside of the for loop:

let i = 0;
let x = 3;
for (; i < 3; i++) {
    console.log(i ** x);
}

The code above will have the same result as the one before.

Note that, as mentioned above, we still need to include the ; from the initialState expression, or else the loop will not function properly.

Condition

The condition defines the point at which the looping execution of the code block will stop. If this expression is omitted, the for statement will not know when to stop, and will continue to loop forever – this is known as an infinite loop. To get around this restriction, you can include a break statement inside the loop, which causes the thread of execution to leave the current code block. An example of this is provided below:

let i = 0;
let x = 3;
for (; ; i++) {
    if (i === 3) break;
    console.log(i ** x);
}

The above code moves the condition into the code block itself, causing execution to stop by using a break statement (if (i === 3) break;).

stateUpdate

This expression is used to describe a change – how the state is updated. If the state is not updated for each loop iteration, and the initial state value meets the condition statement for the loop, the code will produce an infinite loop.

If the stateUpdate expression is omitted, the update must occur somewhere else. For instance, it is possible to update the state inside the code block by modifying the counter variable directly:

let i = 0;
let x = 3;
for (; ;) {
    if (i === 3) break;
    console.log(i ** x);
    i++
}

In the above example, the stateUpdate statement occurs as a part of the for statement’s code block, instead of in the for statement itself.

Note: the for loop’s head is now made of only two semicolons.

Note: the order of operations is important! In order for the loop to function properly, you need to ensure each of the following conditions are met:

  • Make sure the variables you need for the loop’s initialState were assigned a value
  • Create a condition to stop the loop (note – if the console.log() command appears before the stop condition, an additional value (27) will be printed to console)
  • Update the initialState variable before the loop starts again in order to ensure the stop condition can be met.

 

Other frequently used loops

There are several other types of loop statements in JavaScript that can be used in addition to for statements. These include:

  • for…of statement
  • for…in statement (used to loop through Objects)
  • do…while statement
  • while statement
  • various iteration methods for JavaScript Arrays.

 

Related Articles

JavaScript – How to use the for…of Statement

JavaScript – How to Use the for…in Statement

JavaScript – How to Use The Array map() Method

Related Posts

How to Change CSS Using JavaScript

How to Change CSS Using JavaScript

Cascading Style Sheets (CSS) is used to design the layout of a webpage. CSS is a set of structured rules describing the layout of elements in

How to Use the Assignment Operator in JavaScript

How to Use the Assignment Operator in JavaScript

The Assignment operator is used to assign a value to a variable. Assignment (=) The assignment operator simply assigns the value of the right operand to

How to Use the for…in Statement in JavaScript

How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties. Basic for…in loop example The following code demonstrates a basic example using the for…in statement