The Complete Guide to Loops in JavaScript

I know there are plenty of places online (StackOverflow, MDN) that can be an excellent resource for exploring loops and Array iterable methods. But… sometimes it’s good to write about something just so that these patterns settle in your mind and the knowledge is cemented for good. As a result, I found some things I didn’t know existed. In this article I’ll share them with anyone who needs to get a better insight into loops!

The primary purpose of a loop is to iterate over one or a set of multiple statements. Iterating is a commonplace act in software development. To iterate simply means to repeat an action multiple times.

The word “loop.” is printed 3 times. The condition (i >; 1) might deceive you into thinking that the text will be printed 2 times at most.

But it’s printed 3 times! Because counting started with 0 and (i> 1) = 2.

The Infinite for Loop

A for loop can be defined without any of the default statements. But by doing this you will create an infinite for-loop that will freeze your program:

for(;;) console.log("hi"); // Infinite for loop - don't do it

Multiple Statements

Multiple statements can be separated by commas. In the following example, the inc() function is used to increment the value of a global variable counter. Note the combination of the the two statements: i++, inc():

While and continue

Arrays

Many of the Array.* methods are iterators. Instead of passing your array into a for or a while loop you should use built-in Array methods instead. Arrays usually already have methods offering cleaner syntax for anything you would write yourself to solve the same problem. So why re-invent the wheel?

Array methods are attached to Array.prototype property.This means you can execute them directly from array object like array.forEach() or directly from array’s literal value like: [1,2,3].forEach();

Array.forEach

Return value:none

The forEach method will execute a function for every item in the array.

Starting from ES6 it can be suggested to use arrow functions together with Array methods. The code will be easier to read and maintain when building large scale applications. Let’s take a look at how we can make syntax cleaner:

1.) Because in JavaScript functions are also expressions, you can pass the function directly into the forEach method:

As long as you have only one single statement, you can remove {} brackets.

"pear"
"banana"
"orange"
"apple"
"pineapple"

Array.every

Return value:boolean

Not to be confused with the “execute for every item” logic of forEach. In many cases method every will actually not run on every item in the array when at least one item doesn’t evaluate to true based on specified condition.

The method every will return true if the value of every single item in the array satisfies the condition specified in its function argument:

The result is true because none of the numbers in the array are greater than or equal to 10. Let’s take at the same function with a different value set. If 10 or a greater number was present in the array the result would be false:

Here one of the numbers is 256. Which can be translated to “not every value in the array is < 10”. Hence, false is returned. It’s important to note that once Array.every method encounters 256 the condition function will not execute on the remaining items. Just a single failed test will cause false.

Array.every does not modify the original array. The value inside the function is a copy, not a reference to the value in the original array:

Array.map is like Array.forEach but it returns a copy of the modified array. Note that the original array is still unchanged.

Array.reduce

Return value:accumulator

Reducers are similar to other methods. Yet they are unique because they have an accumulator value. The accumulator value must be initialized. There are different types of reducers. In this first example, we’ll take a simple case.

As values are iterated, this accumulator adds all numbers into a single value:

This reducer added up all the numbers into the single accumulator value and returned it: 1 + 2 + 4 = 7.

How to understand reducers in more complex, practical situations?

When developing software in the real world you won’t be using reducers to count numbers. This can be done with a simple for loop. You will encounter plenty of situations where a set of data should be “reduced” only to the set of important values based on some criteria.

Array.reduce or Array.filter?

When it comes to Array methods, always try to to choose a proper tool for the task. Don’t use reduce just because you want to use reduce. You’ll notice that some things you plan to use reduce for can be done with filter.

However, one of the most common use cases for a reducer is updating the application view and/or properties of a database entry, via some API call.

Reducers And Updating Object Properties In A Database

After a database action round trip, you may want to update the application view. But why update all objects everywhere, when you can “reduce” which object properties should be affected, without having to copy the entire object?

Let’s say your car listing management application has a button that updates the price of a particular vehicle. The user sets a new price and clicks on the button. An action is dispatched to update the vehicle in the database. Then the callback function returns containing the object with all properties for that vehicle ID. But, we only need to update the price. A reducer can make sure to update only the price not the entire object. The object is then sent back to the database and the application view is updated.

Creating Your Own Object Iterables With [Symbol.iterator]

In some advanced cases you might be interested in this pattern for creating your own iterable object. To be honest though I can’t think of anything practical. If you know anything about this or have practical experience with Symbol.iterator, post a comment and perhaps then I can update the tutorial.

Our mission: to help people learn to code for free. We accomplish this by creating thousands of
videos, articles, and interactive coding lessons - all freely available to the public. We also have
thousands of freeCodeCamp study groups around the world.