For loops run a block of code for based on a condition that is updated at every iteration of the loop.
This is what a typical for loop looks like:
for (statement 1; statement 2; statement 3) {
// code that runs
}
This executes just ONCE before the execution of the code in the for statement.
This is the condition that is checked before the execution of the code in the for loop.
This is executed every time the code in the for loop finished.
Here's an example of a for loop:
let total = 0;
for (int i = 0; i < 5; i++) { // 0 + 1 + 2 + 3 + 4
total += i;
}
// total = 10
You don't always need to include statement 1 or 3. You DO need a statement 2. So, this is allowed:
let i = 0;
let total = 0;
for (; i < 5;) { // 0 + 1 + 2 + 3 + 4
total += i;
i++;
}
You can add practice problems here if you want. Follow the format below.