Execution context and the call stack — visually illustrated by a slice of tasty cake

Ghost Together
3 min readNov 13, 2018

--

Here’s a list of my best web development tutorials.

Complete CSS flex tutorial on Hashnode.

Ultimate CSS grid tutorial on Hashnode.

Higher-order functions .map, .filter & .reduce on Hashnode.

Follow me @ Twitter, Instagram & fb to never miss premium articles.

Global Scope is created internally by JavaScript as var window = Window() (rough equivalent) behind the veil.

Global Scope acts as the first automatically created Execution Context roughly at the time when the browser opens a URL:

Global Scope is the first Execution Context on The Call Stack.

A new Execution Context (EC) is spawned from a scope containing variable definition and the binding of the this object. Essentially the this object in a given EC is the link to the object context under which it operates:

The binding of the this object across Execution Contexts on The Call Stack.

A new Execution Context is caused by a function call. This new Execution Context is then placed on top of Execution Stack (or The Call Stack).

A new Execution Context can also be created when an object is instantiated — but its only because object instantiation is a constructor function call.

From then on, whatever functions you call or whatever objects you instantiate will cause a new execution context created and pushed onto the stack.

This process repeats while maintaining a this object chain all the way up to the currently executing context (the topmost one):

There is always one currently executing context. The rest are stacked below.

After the function is finished executing, the stack is removed from the top and the code control flow returns to the previous or uppermost execution context.

In other words it’s a LIFO (Last In First Out) order.

Noteworthy: This “stacking” occurs only when you call a function from the scope of another function. And that function calls yet another one from its own scope. Thus, it creates not only a stack of, but also a chain of contexts tied by the this object — related to the scope in which the function was executed.

Stacking will not happen no matter how many function calls are made in the same Lexical Environment and scope. They all just push and pop within the same environment.

Hope this article was helpful. . . and the 🍰 cake’splanations delightful!

Sponsored by Learning Curve — an independent book publishing company that provided these amazing illustrations for free.

You may want to also see this JavaScript Execution Context video tutorial:

JavaScript Execution Context and The Call Stack.

--

--

Ghost Together
Ghost Together

Written by Ghost Together

Ghost Together @ https://semicolon.dev is an alternative to Twitter. Sign up to meet other makers of things.

Responses (7)