For Loop
The for
loop is the most basic loop that repeatedly executes a block of code as long as the given condition is true.
Basic Structure of the for
Loop
for (initialization; condition; update) {
// Code to be executed repeatedly
}
-
Initialization: An expression that is executed once when the loop starts. It is usually used to initialize a variable for the loop.
-
Condition: This condition is checked before each iteration. If it is true, the code block enclosed in curly braces
({ })
is executed. If it is false, the loop stops executing. -
Update: An expression that is executed after each iteration of the block of code. It is often used to increase the value of the loop variable. The increment operator
++
or decrement operator--
are commonly used.
The for
loop will keep executing the code until the specified condition becomes false.
The variable used for initialization, condition, and update is conventionally named i
for "index."
for (let i = 0; i < 3; i++) {
// let i = 0 : initialization
// i < 3 : condition
// i++ : update
}
Examples of Using the 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 from 5 to 1 in reverse order
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.