How to Use the For Loop in JavaScript

09/30/2021

Contents

In this article, you will learn how to use the for loop in JavaScript.

Using the for loop in JavaScript

A for loop is a control structure in JavaScript that allows you to repeat a block of code a specified number of times. The for loop is commonly used when you want to iterate over an array or object, or when you want to execute a block of code a certain number of times.

Syntax

Here is the basic syntax for a for loop:

for (initialization; condition; increment) {
  // code to be executed
}

The initialization statement is executed before the loop starts. It typically initializes a counter variable to a starting value.

The condition is evaluated before each iteration of the loop. If the condition is true, the loop continues. If the condition is false, the loop terminates.

The increment statement is executed after each iteration of the loop. It typically updates the counter variable.

Examples

Here is an example of a for loop that iterates over an array:

const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

In this example, the loop starts with an initialization statement that sets the variable i to 0. The condition is that i is less than the length of the array numbers. The increment statement is i++, which increments i by 1 after each iteration of the loop. The code inside the loop logs each element of the array to the console.

Here is another example of a for loop that executes a block of code a certain number of times:

for (let i = 0; i < 5; i++) {
  console.log("Hello, world!");
}

In this example, the loop starts with an initialization statement that sets the variable i to 0. The condition is that i is less than 5. The increment statement is i++, which increments i by 1 after each iteration of the loop. The code inside the loop logs "Hello, world!" to the console.

Some additional tips for working with for loops in JavaScript:

  • You can use the break statement to exit the loop early if a certain condition is met.
  • You can use the continue statement to skip over certain iterations of the loop if a certain condition is met.
  • You can use the for...in loop to iterate over the properties of an object.
  • You can use the for...of loop to iterate over the elements of an iterable object, such as an array.