JavaScript in depth: execution contexts and event loop (1 of 4).

Luca Di Molfetta
2 min readMar 9, 2024

--

Introduction

During a technical interview for a Front-end Developer position, I was asked a question about a piece of code that, at first, I found really weird.

I knew it was connected to the way JavaScript handles asynchronous programming and to the event loop, but at that moment I couldn’t really remember how it worked. Long story short, I wasn’t able to answer.

The problem

Look at the following code. The question was:

Tell me in what order the statements are logged into the console and which values are printed to the screen.

let fooPromise = new Promise((resolve)=> {
resolve('resolved');
});


for (var i = 0; i < 10; i++) {
let f = i;
setTimeout(() => {
console.log(i);
console.log(f);
}, 0);
}


console.log('this is a console.log');

fooPromise.then((value)=> console.log(value));

If you have even a basic understanding of how Promises work in JS, you may have guessed that the first two statements logged into the console are:

"this is a console.log"
"resolved"

But the weird part happens when it starts to log what is inside the for loop:

10
0
10
1
10
2
10
3
10
4
10
5
10
6
10
7
10
8
10
9

You have probably noticed that, inside the for loop, the loop control variable is declared as a var instead of a traditional const or let.

The reality is that, even for a few lines of code, there is a lot to know to fully understand what happens behind the scenes.

Even if an interview goes wrong, it’s always an opportunity you can use to figure out where you can improve. For this reason, I decided to dive deeper into the inner mechanisms of JS, and I am sharing this information to improve my learning through an active approach.

In order to be able to fully understand the correct answer and why we see that result in the console, I will try to explain in the simplest way possible these key concepts of how JavaScript works:

  1. The difference between JavaScript Runtime, JavaScript Engine and Web APIs.
  2. What are execution contexts in JS.
  3. What is the Event Loop.

At the end, we will put it all together and we will re-analyze the interview’s exercise.

Spoiler alert: It won’t be short. But trust me, I will do my best to make you a more skilled developer by the end of these readings!

Let’s start! You can read step 2 here.

--

--

Luca Di Molfetta

I'm a former Italian Navy Officer who switched careers to become a developer. I'm working as Angular developer @RED (https://red.software.systems/en/home)