For Loop
The for
loop is the most basic loop that repeatedly executes a block of code as long as a specified condition is true.
Basic Structure of the for
Loop
for (initialization; condition; update) {
// Code to be executed repeatedly
}
-
Initialization: An expression that runs once as the loop begins. It is typically used to initialize a variable that will be used in the loop.
-
Condition: This is checked before each iteration. If true, the code block within the curly braces
({ })
will continue to execute; if false, the loop will terminate. -
Update: An expression that executes after each iteration of the code block. It is often used to increment the loop variable. The increment operator
++
or decrement operator--
is commonly used.
The for
loop keeps executing the code as long as the specified condition is met, terminating when the condition evaluates to false.
In initialization, condition, and update, the variable i
is conventionally used to represent an index.
for (let i = 0; i < 3; i++) {
// let i = 0 : initialization
// i < 3 : condition
// i++ : update
}
Examples of Using for
Loop
- Printing numbers from 0 to 4
for (let i = 0; i < 5; i++) {
console.log(i); // Prints 0, 1, 2, 3, 4
}
- Printing all elements in an array
const fruits = ['Apple', 'Banana', 'Cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]); // Prints "Apple", "Banana", "Cherry" in order
}
- Printing numbers in reverse from 5 to 1
for (let i = 5; i > 0; i--) {
console.log(i); // Prints 5, 4, 3, 2, 1
}
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.