Sitemap
Aliajam

Aliajam

JavaScript for loops

3 min readFeb 28, 2020
Press enter or click to view image in full size

JavaScript supports different kinds of loops which I’ll explain in this article, and we will also analyze which one is faster and how they work.

  1. Traditional for loop:
Press enter or click to view image in full size
javascript loops

set a variable before the loop starts (i = 0).

define the condition for the loop to run (i must be less than the length of the array).

Increases a value (i++) each time the code block in the loop has been executed.

It takes 4.194ms to run this loop on my computer. If instead of arr.length we pass the array directly it will run 1 ms faster

the reason is in i < arr.length checks in every loop if i is smaller than the length of arr

but in i < arr every loop cycle checks if arr at position i is truthy.

Press enter or click to view image in full size

Now let’s check other for loops and see which one is faster.

Get Aliajam’s stories in your inbox

Join Medium for free to get updates from this writer.

2. for/of loops through the values of an iterable object.

For/of lets you loop over data structures that are iterable such as Arrays, Strings, Maps, NodeLists, and more.

Press enter or click to view image in full size

As you can see, for/of loop is almost 8 times slower than other forms of loops.

ForEach: forEach() calls a provided callback function once for each element in an array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized.

Press enter or click to view image in full size

2.958ms which has way better performance over other loops.

Loops over objects: Objects are not iterable unless they implement the iterable protocol. Therefore, you cannot use for…of to iterate over the properties of an object. Instead, you have to use Object.keys or Object.entries, to iterate over the properties or entries of an object.

Press enter or click to view image in full size
Press enter or click to view image in full size
Press enter or click to view image in full size

Another option for this use case might be to use a Map:

Press enter or click to view image in full size

--

--