Back to all questions

What is an Execution Context?

Devs Hive

Devs Hive

Seen on interview: 6 users

This question comes up in almost every Frontend or Backend interview at the junior/middle level.

In short, an Execution Context is the environment in which our code is currently running; put simply, it is the value of this at the moment of execution. There are 3 types of execution context:

1. Global Execution Context

This context is created once, when the file is loaded, and it holds all the code that is not inside functions: global variables, global functions, and this at the top level.

In the browser, the global object is usually window.

var x = 10;

function sayHi() {
console.log("hi");
}

console.log(x); // 10

console.log(this === window); // true (але залежить від режиму)

2. Function Execution Context

The key thing to remember here: every function call creates a new context. Even if it is the same function, the context will be different each time. In it, JS stores the function parameters, local variables (ті, що всередині {}), and this for that specific call.

function sum(a, b) {
const result = a + b;

return result;
}

sum(1, 2); // один контекст
sum(5, 10); // інший контекст

3. Module Execution Context

If the code runs as an ES module, it is executed in a module context. It is similar to the global one, but there are 2 important differences:

  1. Variables do not automatically become global
  2. this at the top level will be undefined
<script type="module">
const x = 123;
console.log(this); // undefined
// x не з'явиться як window.x
</script>

Seen on interview?

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!