30 Days Of JavaScript

Day 4: Loops

Lesson 3: For Of

There's a joke in computer science that won't quite make sense to you yet, it neatly illustrates one of the most common causes of bugs in code that the for of loop handles. The joke is:

There are only two hard problems in computer science:

  1. Cache invalidation
  2. Naming things
  3. Off by one errors

There's a couple of jokes in here, but the one we care about is there being one more problem in the list than mentioned in the set up.

This is called an off by one error and is usually down to that whole "arrays start at 0" thing or forgetting to add or remove an equals to an equality check like < vs <= for less than or less than or equal to.

Here's an example

You can see in the code above that while I have used the handy .length array property to get it's length, I've used <= for the loop condition. So rather than looping through 4 elements the loop runs for 5 iterations and there is no 5th element for this array.

We could of course fix it by changing the <= to a simple < but wouldn't it be nice if we could just skip this type of problem all together?

Well, let me introduce you to the for of loop.

Here we replace the conditions part of the for loop declaration (the bit between the ( )) with const age of ages.

Which is a quick way of saying:

We are going to loop over ages, and for each element of ages we are going to create a new, temporary variable called age that stores the iterations age in so we can use it in the loop.

You can see from the console.log()'s that it works, and at no point did we have to worry about counters, end conditions or off by one errors.

This is your first taste of something called declarative programming. So far (and most of the time in the future) you have mainly written imperative code, which is where you give very explicit instructions to the computer, setting up counters and if statements and the like.

In this case you have simply said "loop over this array and give me the element on each iteration". You have no idea how the computer is executing this under hood. It's probably using a for loop, working out the length etc, but it could be using a while loop. You don't know, and you don't need to.

Much of modern development is moving toward a declarative style, but for now it is just nice to have the extra information.

You still need to be comfortable with for loops, while loop and for of loops 😆

Outline

Go Pro?

Upgrade to Pro for quizzes, tracked progress and a completion certificate for just $25 🚀

Want more developer tips, tricks and tools?
Then follow me:
FREE Coding Career Quick Start Guide 🚀
Discover the best way to learn to code, how to land a job and valuable resources to help your journey in this free 15 page value packed guide.
Looking to email me? You can get me on my first name at allthecode.co