for loop in javascript

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

index.tsx
for (initialization; condition; iteration) {
  // code to be executed
}
72 chars
4 lines

The initialization statement is executed once at the beginning of the loop, and typically initializes the counter variable.

The condition statement is evaluated at the beginning of each iteration of the loop. If the condition is true, the loop continues; if it is false, the loop terminates.

The iteration statement is executed at the end of each iteration of the loop, and typically increments or decrements the counter variable.

For example, the following code uses a for loop to print the numbers 1 through 5 to the console:

index.tsx
for (var i = 1; i <= 5; i++) {
  console.log(i);
}
51 chars
4 lines

This code initializes a variable i to 1, tests whether i is less than or equal to 5, and increments i by 1 each time through the loop. The console.log(i) statement is executed each time through the loop, printing the value of i to the console.

You can use a for loop to iterate over arrays and objects as well. For example:

index.tsx
var arr = [1, 2, 3, 4, 5];

for (var i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}
92 chars
6 lines

Here, the for loop initializes i to 0, tests whether i is less than the length of the arr array, and increments i by 1 each time through the loop. The console.log(arr[i]) statement is executed each time through the loop, printing the value of each element in the array to the console.

gistlibby LogSnag