JavaScript Function Execution Context — What Happens When a Function Is Called
Most JavaScript bugs don’t happen because of syntax. They happen because developers don’t understand what happens when a function runs.
That behavior is controlled by the Function Execution Context (FEC).
If Global Execution Context explains how a program starts, Function Execution Context explains how functions actually work.
What Is a Function Execution Context?
A Function Execution Context is created every time a function is invoked.
Important points:
Just Like GEC, FEC Has Two Phases
Every Function Execution Context also has two phases:
This is critical. Functions do not behave differently from global code — they follow the same rules.
Example Code
var x = 10;
function add(a, b) {
var result = a + b;
return result;
}
add(2, 3);
Let’s see what happens internally.
Phase 1: Memory Creation Phase (Inside the Function)
When add(2, 3) is called, JavaScript creates a new Function Execution Context.
During memory creation:
Memory looks like this:
a = 2
b = 3
result = undefined
No calculations yet.
Phase 2: Execution Phase
Now JavaScript executes the function line by line:
Recommended by LinkedIn
result = a + b; // 5
return result;
Multiple Function Calls = Multiple Contexts
function outer() {
inner();
}
function inner() {
console.log("Hello");
}
outer();
Call stack behavior:
This is why stack overflows happen with infinite recursion.
Why This Matters in Real Applications
Example Bug
function calculate() {
console.log(total);
var total = 100;
}
Output:
undefined
Why?
This is hoisting inside function scope, not magic.
Relation to Scope and Closures
If this concept is clear, closures become obvious instead of scary.
Key Takeaways
Final Thought
JavaScript does not “run functions”. It creates execution contexts and manages them carefully.
Once you understand Function Execution Context, you stop guessing and start predicting behavior.
#JavaScript #React.js #React #Node.js