Loading lessons...
JavaScript For Loop
JavaScript For Loop
A loop runs the same code over and over. The for loop is the most common.
The for syntax
for (statement 1; statement 2; statement 3) {
// code to run each time
}
- statement 1: runs once at the start (the counter).
- statement 2: the condition checked before each loop.
- statement 3: runs after each loop (usually increment).
A counting example
for (let i = 0; i < 5; i++) {
console.log(i);
}
This prints 0, 1, 2, 3, 4.
Loop through an array
let fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
Breaking it down
let i = 0starts the counter.i < 5is checked; if true, the block runs.i++adds 1 after each run.- When
ireaches 5, the condition is false and the loop stops.
TL;DR
forloops repeat code a set number of times.- Three parts: start, condition, step.
- Great for counting and looping through arrays.