We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

The Call Stack

Click to play video

So, we know that JavaScript has one main thread, and that it's non-blocking. So how do these "background" tasks (like HTTP requests, setTimeout, etc.) get executed? Well, it's via the event loop - but first, we need a little refresher on the call stack.

This next bit assumes you know about stacks, heaps, and the call stack. If you don't, review our memory management course first. That said, I'll give you a quick refresher. Every time a function is called, it gets added to the top of the call stack. When the function returns, it gets popped off the stack.

Let's say we have this code:

function startJob() {
  console.log("Job started");
  workOnJob();
}

function workOnJob() {
  console.log("Working on job");
  finishJob();
}

function finishJob() {
  console.log("Job finished");
}

startJob();

The call stack will grow like this as each function is called:

                                     -> finishJob
                        -> workOnJob    workOnJob
[empty]    -> startJob     startJob     startJob

Then as each function returns, it gets popped off the stack:

finishJob  ->
workOnJob     workOnJob ->
startJob      startJob     startJob  -> [empty]

Long story short - JavaScript's call stack works the same way as any other language's call stack. But what happens when we encounter asynchronous code? We'll cover that in the next lesson.