for(var i = 0; i < 10; i++) {
console.log(i);
}
The above loop will run for 10 times exactly and then stop. Here’s what’s going on here:
This code declares a variable called i, and sets it equal to 0. This code runs before any loops are run. This section is only ever run once at the start of the loop process.
The loop then checks this statement to see if it returns true. This statement in question is ‘is the variable i less than the value 10?’. Because our variable i is set to 0, this will return TRUE, and so the loop will run. The statement here is what’s known as a condition. We will explore more about conditions later.
After the block of code inside the curly brackets is run, this is then executed. Remember when we see this i++ it is an arithmetic operation, that is the equivalent to i = i + 1. The code here simply adds 1 to our i variable. You can perform any operation here; you are not just limited to adding 1.
console.log(i)
}
This is the code that will be executed each time our loop is run.
The loop order of events is as follows:
It’s important to understand that when we define our condition statement, we must define a condition that can ‘break’ or the loop will run forever. This just means that we must write a condition that will at some stage return FALSE as a result of our loop running.
Let’s see a for loop in the context of looping through an array and picking off values.