JavaScript: Useful Loops and When to Use Them

JavaScript: Useful Loops and When to Use Them

Loops are a simple concept: do a thing some number of times. JavaScript gives us a lot of ways to do that, and each one is useful in it's own way.

These are the 5 Basic JavaScript Loops:

  1. while
  2. do...while
  3. for
  4. for...of

There is a sixth loop called for await...of but that's advanced stuff we won't cover here. Arrays also have some loop-like methods like .forEach() and .map() but they aren't true loops, so we won't cover those here either. Now that's out of the way...

1. The while Loop

First appearance: JavaScript ES1, 1997

The while loop is the most basic. It takes a single expression and if that expression evaluates to true, the code in the loop will run. This process repeats until the expression evaluates to false and the loop exits.

Here's an example:

// We have an empty poker hand, and we need 5 cards
let pokerHand = []

// We can use the length of the hand as the condition
while (pokerHand.length < 5) {

WARNING: Pay attention to the details in your while loops - it's easy to get caught in an infinite loop if you forget to change the variables involved in the condition!

When to use while

  • The loop condition is simple
  • The code inside the loop doesn't need to know how many iterations have passed

2. The do...while Loop

First appearance: JavaScript ES1, 1997

This one is exactly the same as the standard while except it will always run once. A regular while loop evaluates the expression, then runs the block, so it may never run. The do...while runs the code block first, then evaluates the condition. Beyond that, using this is mostly personal preference

Here's our example re-written as a do...while loop:

let pokerHand = []
  pokerHand.push(drawCard()) // This will always run once
while (pokerHand.length < 5)

When to use do...while

  • You like the syntax better than while
  • AND the loop can always run at least once (because it will)

3. The for Loop

First appearance: JavaScript ES1, 1997

Like the others, a for loop runs a code block until a condition evaluates to false, but with an added punch: a for loop tracks how many times it has run!

To be fair, a while loop can do this too:

let i = 0
while (i < 5) {
  i++ // adds one to `i` every time the loop runs

So why do we need for loops at all? Well the for makes that process easier by letting you declare all 3 of those pieces - the variable, the expression and the incrementing - in one line! Here's that same loop written with for:

/*   ↓ Initialize variable
     ↓          ↓ Add the looping condition
     ↓          ↓      ↓ Increment the variable at the end of the loop */
for (let i = 0; i < 5; i++) {
  /* do some stuff */

When to use for

  • When the code inside the loop needs to know the number of the loop iteration

4. The for...of Loop

First appearance: JavaScript ES6, 2015

A later addition to the language, for...of is designed specifically to iterate over the values of objects (but only iterable objects like Arrays, Maps and Sets. This doesn't work for object literals). So instead of using an expression to determine how many times to run, the loop will just run one time for every value inside the object.

Here's what it looks like:

let namesArray = ["Joe", "Hannah", "Chris"]

for (let name of namesArray) {
// Console Output:
// "Joe"
// "Hannah"
// "Chris"

That loop will run 3 times because there are 3 elements in the array, and each time the value of name will change to the next element.

When to use for...of

  • You need to iterate over a list of data
  • The code inside the loop doesn't need to know how many iterations have passed

5. The Loop

First appearance: JavaScript ES1, 1997

This one is WEIRD. Where for...of iterates over the values of an object, iterates over its properties instead - and it does work for Object literals. The syntax looks the same, but the output is very different.

Let's look at that last example as a loop:

let namesArray = ["Joe", "Hannah", "Chris"]

for (let name in namesArray) {
// Console Output:
// 0
// 1
// 2

Weird, right? The printed the index of each element because those are the properties of an array object. That might make more sense looking at an object literal:

let user = { name: "Joe", age: 30, state: "Arizona" }

for (let property in user) {
// Console Output:
// name
// age
// state

Again, the properties of the object are being printed here. This could be a useful alternative to for...of for object literals because you can access the values using the properties, like this:

let user = { name: "Joe", age: 30, state: "Arizona" }

for (let property in user) {
// Console Output:
// Joe
// 30
// Arizona

But there are better ways to do that, like using Object.values(user) to get an array of all the values and iterating over that.

And there are pitfalls. The order of the properties is random, and the loop will ignore any Symbol or method properties because those aren't enumerable. Consider this a special case loop that you won't reach for often - if at all. The only time I ever use it is when I accidentally type in instead of of (that's an easy way to lose an hour of time debugging your code).

Thanks for reading! For more content like this, follow me on Twitter @justmyrealname and here on Hashnode Joe Ziemba!