JavaScript For Loop

please click here for more wordpress cource

A for loop in JavaScript is a control flow statement that allows you to repeatedly execute a block of code a certain number of times. The syntax for a for loop is as follows:

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

The initialization step initializes the loop variable before the loop starts. This step is optional, and you can skip it if you want to.

The condition step is the condition to be evaluated before each iteration of the loop. If the condition is true, the loop continues; if it is false, the loop terminates.

The increment/decrement step updates the loop variable after each iteration. This step is also optional.

Here’s an example of a for loop that iterates through an array of numbers and logs each number to the console:

const numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
  console.log(numbers[i]);
}

In this example, the initialization step initializes the variable i to 0, the condition step checks if i is less than the length of the numbers array, and the increment step increments i by 1 after each iteration. The loop will iterate five times, logging each number to the console.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *