Understanding the basics of “for” & “while” loops in JavaScript.

Loops are a very important concept in JavaScript. Loops are a set of instructions used to repeat the same block of code till a specified condition returns either true or false (depending on what you need). Javascript supports different kinds of loops such as for, for/in, while and do/while. I will be covering “for” and “while” loops.

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 —

begini = 0 → this executes upon entering the loop

conditioni < 4 → the condition is checked before the loop iteration. If false, the look will stop.

bodyconsole.log(i) → it will console log i as long as the condition is truthy.

step 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 condition test, body and 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!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store