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.tsx72 chars4 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.tsx51 chars4 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.tsx92 chars6 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