How JavaScript Executes Code: Hoisting, undefined & Call Stack

How JavaScript Executes Code: Hoisting, undefined & Call Stack Explained Clearly

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);
Learn JavaScript
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");
}
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 ≠ moving code
Hoisting = memory preparation before execution

4. Execution Phases

Memory Phase

x → undefined
getName → function stored

JavaScript scans the code and prepares memory.

Execution Phase

getName() → executed
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");
}
Error: not a function

7. Call Stack

Call Stack manages execution order using LIFO (Last In First Out).

function greet(){
  console.log("Hello");
}

greet();
console.log("End");
Hello
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 🚀

Chakrapani U

Hi, I’m Chakrapani Upadhyaya, an IT professional with 15+ years of industry experience. Over the years, I have worked on web development, enterprise applications, database systems, and cloud-based solutions. Through this blog, I aim to simplify complex technical concepts and help learners grow from beginners to confident, industry-ready developers.

Previous Post Next Post

نموذج الاتصال