Skip to main content

JavaScript For Loop

A for loop in JavaScript is a type of loop that allows you to iterate over a block of code a certain number of times.

The syntax of a for loop is as follows:

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

Explanation:

  • initialization: This is typically used to initialize a counter variable that is used to keep track of how many times the loop has executed. This is only executed once before the loop starts.

  • condition: This is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, the code inside the loop is executed. If the condition is false, the loop exits.

  • iteration: This is usually used to increment or decrement the counter variable. This is executed after each iteration of the loop.

Here's an example of a for loop that prints the numbers 0 through 4 to the console:

for (let i = 0; i < 5; i++) {
console.log(i);
}

In this example:

  • let i = 0 initializes the counter variable i to 0. i < 5 is the condition that checks if i is less than 5.
  • As long as i is less than 5, the loop will continue to execute. i++ increments i by 1 after each iteration of the loop.
  • Inside the loop, console.log(i) prints the current value of i to the console.

Different Kinds of Loops

There are several different kinds of loops in JavaScript that you can use to repeat a block of code a certain number of times or until a certain condition is met.

Some of the most commonly used loops are:

  • for loop: This is the most commonly used loop in JavaScript. It allows you to iterate over a block of code a specific number of times. See the previous answer for an example of a for loop.

  • while loop: This loop will continue to execute as long as the condition is true.

  • do-while loop: This loop is similar to the while loop, but it will always execute at least once, even if the condition is false.

  • for...in loop: This loop is used to iterate over the properties of an object.

  • **for...of loop:** The for...of loop is a type of loop in JavaScript that allows you to iterate over the elements of an iterable object, such as an array or a string.

The For Loop example

You can also use a for loop to iterate over the elements of an array:

Editor

Loading...

In this example:

  • HTML code creates an unordered list (<ul>) with an ID of fruitsList.
  • Uses JavaScript to iterate over the fruits array and create a list item (<li>) for each fruit.
  • The text content of each list item is set to the corresponding fruit from the array using innerText, and the list item is added to the ul element using appendChild.