-1

Since JavaScript is single threaded environment and there is Event Loop which is executing all the queued tasks, then why is [].forEach(() => {}); not executed asynchronously?

console.log("1");
[2].forEach(value => console.log(value));
console.log("3");

Output: 1 2 3

Why output will not be 1 3 2

Why callback function within .forEach method is blocking the next line of code.

Tân
  • 1
  • 15
  • 56
  • 102
Kumar Raj
  • 35
  • 1
  • 4
  • 2
    Why did you expect otherwise? `forEach` is synchronous. If it was asynchronous, you should expect `3 1 2` anyway. – jonrsharpe Dec 23 '19 at 17:45
  • Does this answer your question? [Callback after all asynchronous forEach callbacks are completed](https://stackoverflow.com/questions/18983138/callback-after-all-asynchronous-foreach-callbacks-are-completed) – Tân Dec 23 '19 at 17:58

2 Answers2

0

Javascript is a synchronous language. It will not execute a piece of code until the code before it has been executed.

There are ways to get around it for example you could use a setTimeout function to wait a few moments before executing the forEach loop and you would then see the result 1, 3, 2.

T. Short
  • 3,481
  • 14
  • 30
0

Array.prototype.forEach() doesn't queue tasks to be executed on future event loops, it executes each function immediately, in the current event loop.

This is the default behavior of most functions in javascript as it's a synchronous language. If you require asynchronous behavior, you have to opt into it using things like setTimeout and natively asynchronous functions (mostly file i/o and network requests).

Klaycon
  • 10,599
  • 18
  • 35