- Allows us to iterate over array elements.
- Consists of initialization, condition, and afterthought.
for (initialization; condition; afterthought) { /* code */ }
for (let i = 0; i < 4; i++) {
console.log(i); // Output: 0, 1, 2, 3
}
- Usually initializes a loop counter.
- Loop runs until this condition is false.
- Updates the loop counter's value after each iteration.
- Calls a function once for each element in an array.
let fruits = ["peach", "apple", "lemon"];
fruits.forEach(function(fruit) {
console.log(fruit);
});
- A more concise alternative to forEach loops.
let fruits = ["peach", "apple", "lemon"];
for (let fruit of fruits) {
console.log(fruit); // Output: peach, apple, lemon
}
for
loops offer precision and flexibility.forEach
andfor of
loops iterate through entire arrays;forEach
is similar to other array functions, whilefor of
is concise.- Choice depends on requirements and personal preference.
- There are various other loops available, such as
for in
,while
, anddo…while
.
Happy coding!