DEV Community

Cover image for What is the Execution Context in Javascript?
Terry Threatt
Terry Threatt

Posted on

What is the Execution Context in Javascript?

Javascript is quite often referred to as the most loved program and the most hated programming language. This is because for people new to Javascript there needs to be some understanding of what's going on under the hood. So we are going to focus on the Execution Context to learn how every line of code is executed in Javascript.

Execution Context

The Execution Context is the environment in which the code is being recognized and executed. Everything happens inside an Execution Context in Javascript. when Javascript starts in the browser the beginning Execution Context is always the Global Execution Context and refers to the window object. When a new function is created and executed a new Execution Context is created called the Function Execution Context and it refers to the function object.

// this function creates a function execution context 
function sayHi(name) {
    let greeting = `Hi, ${name}`
    return console.log(greeting)
}
Enter fullscreen mode Exit fullscreen mode

The Execution Context is made up of two whole parts. The Local Memory, which saves contents inside of the current context into space in memory like variables or functions inside the execution context. Also, The Thread of Execution, which travels through the Execution Context for instance a function execution context, and executes each line in the function.

Call Stack

Javascript is a single-threaded and synchronous language. Meaning each piece of code is read one line at a time through one single thread of execution at a time. In order to efficiently keep track of each execution context in a program, Javascript takes advantage of a Last In, First Out data structure called the Call Stack. New execution contexts are pushed into the call stack starting with the global execution context as they are created and popped off the call stack when they are executed.

Call Stack

Let's chat about context

So now you know how the execution context is flowing through your Javascript code. If you enjoyed this post feel free to leave a comment about your thoughts and experiences working with the execution context.

Happy Coding,
Terry Threatt

Top comments (0)