Thrown for a Loop

Daniel C Reyes
2 min readMay 10, 2021

While continuing working on algorithms the very basic of loops remain a very important concept in JavaScript. Loops to keep it simple are a set of instructions used to repeat the same block of code until a specific condition returns either truthy or falsely. Javascript supports a few different kinds of loops such as the for loop, for/in the loop, while loop, and do/while loop. I will be going over “for” and “while” loops in very basic terms.

The “For “ Loop

The “for ” loop is one of the most commonly used loops. Down below you can see the structure of how to create a “for” loop.

We can go over the statement above like this step by step

  • first , i = 0 this executes upon entering the loop
  • next, the condition is set ,i < 5,the condition is checked before the loop iteration. If false, the look will stop.
  • the last step is, i++ ,will execute after the body of each iteration.

Under the hood of all of this, it will run just like this: the first step executes only once, and then it iterates: after each condition test, the last step is executed.

The “While” loop

When we need to repeat actions in a function we can use “while” loops, for example, if you wanted 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. While loops can keep our code DRY without having to write repeated lines of code.

The proper structure a for while loop looks like this:

while the condition is truthy, the code that’s in the body of the loop will be executed.

With the following example… the loop that you see below console logs

i while i < 5

A single execution of a loop is called an iteration and the above example makes five iterations.

Loops are very important to keep your code simple and clean.

--

--