loading...

What is the execution context in JS?

javila35 profile image Joe Avila Updated on ・2 min read

If you've written any code in Javascript, you've interacted with the execution context and execution stack. It's a high-level concept that happens behind the scenes of javascript. You don't need to know anything about it to start coding in Javascript. But understanding the basics will help you avoid code that won't execute, and understanding it well will help you debug code that executes in a way you don't expect.

Loading a javascript file into a browser creates a global execution context. Every time a function in that global context is called, a new function execution context is added to the execution stack. The last function called is the first function to be cleared off the stack. This is referred to as Last In First Out (LIFO).

The execution context is removed from the stack after executing a return statement, or all code has been parsed. There can only ever be one execution context running at a time, but that execution context may be paused at any time to enter a new execution context. ECMAScript refers to this as the running execution context.


An execution context contains at least three properties: a variable object, a scope chain, and thisBinding.

Variable Object

The variable object contains the variables and functions declared inside of the current execution context, and if this execution context was created by a function it also contains the function arguments. This is when hoisting happens, you can read my article about that.

Scope Chain

Contains the current variable object as well as the variable object of the outer context (execution context on the stack one below the current execution context) variable object. If the current execution context is the global execution context there is no outer context.

thisBinding

Gives the current execution context access to this keyword.

Posted on by:

javila35 profile

Joe Avila

@javila35

Full stack software engineer working for Collinear Group.

Discussion

pic
Editor guide