The JavaScript Thread of Execution, Visually Explained

Paul Ryan

This is the first in a series of articles looking at how JavaScript works internally. I will try to make it interesting and not bore you as I know this stuff can sometimes get really tedious!

Imagine being a pilot and now knowing how a plane flies, every day we run our JavaScript code but do we know how it runs?

Let’s Talk About the JavaScript Thread of Execution

Ok, let’s bang out some simple JavaScript code:

const num = 3;

function addOne(x) {
  const result = x + 1;
  return result;
}

const output = addOne(num);

The code above is nothing to get excited about but will serve us well to demonstrate the thread of execution.

When our JavaScript is executed, the code is being stepped through line by line (single-threaded), so in our code above the first line is:

const num = 3;

The next question is, what happens when it steps onto this line? Where does num get stored?

num gets stored in the global memory/execution context, visually it looks like this:

Animation showing how line is executed

So then we move onto the next line:

function addOne(x) {

It’s important to note that we are declaring a function here and not executing one. Therefore, we store the function name with the value of the entire function.

Animation showing how 2nd line is executed

The - f - above is just shorthand for the entire function.

Now we move onto the next line, some of you may think the next line is the body of the function but since we are only declaring the function and not running it, the next line to run is:

const output = addOne(num);

Similar to above, we send the label output to memory but with no value yet as we must run our function.

Saving function label

Now comes the fun part! Actually executing our addOne function.

When a function is executed, it is added to the call stack. The call stack always has global/main at the bottom, we now will push on addOne(3).

Call stack visualized

We also create an execution context for that function. Any variable declared in the function will be added to the function’s execution context.

The first variables that will be added are the function’s arguments, in our case x.

Adding function argument

Now we move onto the next line and store result in the execution context.

Storing result

On the next line, we hit the return keyword which marks the end of a function. We pop addOne() from the call stack and give output a value which is 4.

So first pop addOne from the call stack.

Pop from call stack

Now our last step, assigning the value 4 to the output variable.

last step

Done!

So that’s it! I hope this demonstrates how our JavaScript code is stepped through. I know I only touched off the call stack and execution context in this article but we will be delving deeper into them in the future.

  Tweet It

🕵 Search Results

🔎 Searching...