The “for ” loop is the most commonly used loop. Below you can see a format of how to create a for loop.
We can go over the statement above like this step by step —
i = 0 → this executes upon entering the loop
i < 4 → the condition is checked before the loop iteration. If false, the look will stop.
console.log(i) → it will console log i as long as the condition is truthy.
i++ → this will execute after the body of each iteration.
Under the hood of all of this, it will run just like this:
begin executes only once, and then it iterates: after each
step are executed.
When we need to repeat actions we can use “while” loops, let’s say you want to run the same code for each number from 1–10. While loop can in that case keep our code clean while getting the output we want. Because why would you want to write the same lines of code multiple times? That’s a big NO!
The proper syntax for while loops looks something like this:
So… while the condition is true, the code that’s in the loop body will be executed…
Let’s work with the following example… the loop that you see below console logs i while
i < 4
A single execution of a loop is called an iteration and the above example makes four iterations.
Loops are very important to keep your code simple and clean. I hope this article simplifies the fundamentals of loops. If you have any suggestions to improve this article please do not hesitate to reach out!