0
0
Javascriptprogramming~5 mins

Function execution context in Javascript

Choose your learning style9 modes available
Introduction

Function execution context is how JavaScript keeps track of what to do when a function runs. It helps the computer remember variables and where it is inside the function.

When you want to understand how variables inside a function work.
When debugging why a function behaves a certain way.
When learning how JavaScript runs your code step-by-step.
When you want to know why some variables are not accessible outside a function.
When you want to understand how JavaScript manages multiple functions running at the same time.
Syntax
Javascript
// No direct syntax to write for execution context, it happens automatically when a function runs
function example() {
  // code here
}
example();

Execution context is created automatically when a function is called.

It stores information like variables, parameters, and the place in code where the function was called.

Examples
When greet runs, a new execution context is created to hold name and message.
Javascript
function greet(name) {
  let message = `Hello, ${name}!`;
  console.log(message);
}
greet('Alice');
Each time add runs, it creates its own execution context with a and b.
Javascript
function add(a, b) {
  return a + b;
}
let sum = add(3, 4);
console.log(sum);
Sample Program

This program shows how the function multiply creates an execution context to store x, y, and result. The values inside the function are separate from outside.

Javascript
function multiply(x, y) {
  let result = x * y;
  console.log(`Inside function: result = ${result}`);
  return result;
}

let output = multiply(5, 6);
console.log(`Outside function: output = ${output}`);
OutputSuccess
Important Notes

Each function call creates a new execution context, even if the same function is called multiple times.

Variables inside a function are not visible outside unless returned or passed out.

Understanding execution context helps with debugging and writing better code.

Summary

Function execution context is created automatically when a function runs.

It keeps track of variables and parameters inside the function.

Helps JavaScript know what to do step-by-step inside functions.