This is the first in a series of articles on looking at how JavaScript works. I will try to make it interesting and not bore you as I know this stuff can sometimes get really boring!
Imagine being a pilot and now knowing how a plane flys, every day we run our JavaScript code but do we know how it runs?
Let's talk about the Thread of Execution
Ok, let's bang out some simple code.
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, it steps through line by line (single-threaded), so in our code above the first line is:
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:
So then we move onto the next line.
It is 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.
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:
Similar to above, we send the label output
to memory but with no value yet as we must run our function.
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)
.
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
.
Now we move onto the next line and store result
in the execution context
.
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
.
Now our last step, assigning the value 4
to the output
variable.
Donzo
So that is it! I hope this demonstrates how our code is stepped through. This was a time-consuming article due to creating all the gifs so let me know if you like them or not. 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.
Conclusion
Any questions on the above, feel free to contact me on my socials! ❣️
Top comments (0)