Learn Programming Fundamentals
1 Programming Fundamentals
2 Variables Data Types
3 Conditional Structures
4 Strings
5 Arrays
6 Objects
8 Functions
A for loop is a control flow statement that allows you to execute a block of code repeatedly for a fixed number of times. It is particularly useful when you know in advance how many times you want to execute a certain block of code.
Here's the basic structure of a for loop:
for (initialization; condition; incrementOrDecrement) { // Code to be executed }
This part initializes a loop control variable and is executed before the loop begins. It usually initializes a counter variable to keep track of the number of iterations.
This part defines the condition for executing the loop. The loop continues to execute as long as this condition evaluates to true.
This part specifies how the loop control variable is modified after each iteration. It's typically used to increment or decrement the loop counter.
Let's look at an example:
for (let i = 0; i < 5; i++) { console.log("Iteration: " + i); }
In this example:
let i = 0
initializes the loop counter i
to 0.i < 5
specifies that the loop should continue as long as i
is less than 5.i++
increments the value of i
by 1 after each iteration.The loop will execute five times, with i
taking on the values 0, 1, 2, 3, and 4 in each iteration. After the fifth iteration, the condition i < 5
will evaluate to false, and the loop will terminate.