How to use for loop in Javascript

By FoxLearn 12/18/2024 7:07:26 AM   12
In JavaScript, a `for` loop is used to repeatedly execute a block of code a specific number of times.

It consists of three parts: initialization, condition, and iteration.

  • Initialization: Sets the initial value of the counter variable.
  • Condition: Specifies the condition that must be true for the loop to continue.
  • Increment/Decrement: Updates the counter variable after each iteration.

Here is the syntax of a for loop in JavaScript:

for (initialization; condition; increment/decrement) {
  // code to execute
}

Let's break it down with an example:

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

In this example:

  • Initialization: let i = 0 sets i to an initial value of 0.
  • Condition: i < 5 ensures the loop continues as long as i is less than 5.
  • Increment: i++ increases the value of i by 1 after each iteration.

The code inside the loop (in this case, console.log(i)) will execute repeatedly until the condition becomes false, printing the value of i to the console in each iteration.