JavaScript for loop

The JavaScript for loop is a control structure that allows you to repeat a block of code a specified number of times. The for loop consists of three parts: the initial expression, the condition, and the final expression. These parts determine the start, end, and the increment of the loop.

Syntax of the JavaScript for loop:

1for (initial expression; condition; final expression) { 2 // code to be executed 3}

The initial expression is executed before the loop starts and is usually used to initialize a counter variable. The condition is evaluated at the beginning of each iteration of the loop. If the condition is true, the code inside the loop is executed. If the condition is false, the loop terminates. The final expression is executed at the end of each iteration of the loop and is usually used to update the counter variable.

Here's an example of how to use the for loop to print the numbers from 1 to 5:

1for (let i = 1; i <= 5; i++) { 2 console.log(i); 3} 4 5// Output: 6// 1 7// 2 8// 3 9// 4 10// 5

In this example, the initial expression is let i = 1, which initializes the counter variable i to 1. The condition is i <= 5, which means that the loop will continue to execute as long as i is less than or equal to 5. The final expression is i++, which increments i by 1 at the end of each iteration of the loop.

The JavaScript for loop provides an efficient and convenient way to repeat a block of code a specified number of times. You can use it to iterate over arrays, objects, and other data structures to perform actions.