Sitemap
Leland Zach

Leland Zach

Learning to code and teaching it as I go

Member-only story

Beginner Goodies: Is JavaScript Array.forEach Asynchronous?

2 min readAug 21, 2019
Press enter or click to view image in full size
Guide for JavaScript Loops and their execution caveats
Do JavaScript loops run asynchronously?

If you have ever tried to do some operation in a JavaScript loop that caused out-of-order results, here is why.

Is Array.forEach Asynchronous?

It is not asynchronous. It is blocking. Those who first learned a language like Java, C, or Python before they try JS will get confused when they try to put an arbitrary delay or an API call in their loop body.

Say you try this:

The code executes in order, and the next loop iteration does not begin executing until the previous one has completed its final line.

You will probably expect for the setTimeout to hold up the execution until the length of time of your delay has passed. This is not the case, because the setTimeout method actually returns a value immediately. In Node.js it returns a Timeout object, and in the browser it returns a number that points to the timeout instance.

When something is returned, the next line begins to execute. So you end up getting this effect where the program…

--

--

Leland Zach
Leland Zach

Written by Leland Zach

Learning to code and teaching it as I go