Definition:
Execution in JavaScript means how the JavaScript engine reads, prepares, and runs your code step by step. Before running any line, JavaScript creates memory and then executes code.
Why it is Important:
Understanding execution helps you:
- Avoid bugs
- Understand hoisting clearly
- Debug undefined errors
- Write better optimized code
Understanding JavaScript execution flow
1. Basic Example
var x = 7;
function getName(){
console.log("Learn JavaScript");
}
getName();
console.log(x);
7
Explanation:
- Function executes first
- Then variable value is printed
2. Changing Order
getName();
console.log(x);
var x = 7;
function getName(){
console.log("Learn JavaScript");
}
undefined
Explanation:
- Function is available before execution
- Variable exists but value is not assigned yet
3. Hoisting Concept
Hoisting means JavaScript prepares variables and functions in memory before execution.
Hoisting = memory preparation before execution
4. Execution Phases
Memory Phase
getName → function stored
JavaScript scans the code and prepares memory.
Execution Phase
console.log(x) → undefined
x = 7 → assigned
Code runs line by line after memory is ready.
5. undefined vs not defined
undefined
console.log(a); var a = 5;
Variable exists but value is not assigned yet.
not defined
console.log(b);
Variable does not exist → ReferenceError.
6. Function vs Arrow Function
Function Declaration:
getName();
function getName(){
console.log("Hello");
}
✔ Works because function is fully stored in memory
Arrow Function:
getName();
var getName = () => {
console.log("Hello");
}
7. Call Stack
Call Stack manages execution order using LIFO (Last In First Out).
function greet(){
console.log("Hello");
}
greet();
console.log("End");
End
Execution Flow:
- Global context starts
- greet() pushed to stack
- Executed and removed
- Back to global
Conclusion
JavaScript first prepares memory, then executes code step by step. Understanding this removes confusion around hoisting and undefined.
You now understand JavaScript execution like a pro 🚀