Loops can execute a block of code a number of times. They are perfect for situations where you need to run the same code over and over again, each time with a different value.
The for loop has three optional expressions, separated by semicolons:
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
A simple loop that counts from 0 to 4:
for (let i = 0; i < 5; i++) {
console.log("The number is " + i);
}
For loops are most commonly used to iterate over arrays.
const cars = ["BMW", "Volvo", "Saab", "Ford"];
for (let i = 0; i < cars.length; i++) {
console.log(cars[i]);
}
let to declare your counter variable (like
i). This ensures the variable is only available inside the loop's block
scope.
Expressions in a for loop are optional. For example, you can omit the first
expression if your values are already set:
let i = 2;
let len = cars.length;
for (; i < len; i++) {
text += cars[i];
}
for loop is the most versatile looping structurelet) is the best practice for loop
counters