Curriculum
Module 05 // Core JavaScript
Function Fundamentals
Module Objective
Function declarations vs expressions, parameters, return values, recursion
Mental Model Realtime Simulation
INTERACTIVE_CANVASEditor_Pane
Loading...
Console_Output
Waiting for output...
Practical Code Examples
// Example 1
// 1. Declarations are Hoisted
console.log(sayHi()); // "Hi!" ✅ Works
function sayHi() {
return "Hi!";
}
// Expressions are NOT hoisted
// console.log(sum(1, 2)); // ❌ ReferenceError
const sum = (a, b) => a + b;💡 Function declarations are moved to the top of their scope during the creation phase. Expressions are not, behaving like any other variable.
// Example 2
// 2. Default Parameters
function setRole(user, role = 'guest') {
console.log(`User ${user} is a ${role}`);
}
setRole("Subhajit", "admin"); // "Subhajit is a admin"
setRole("Alex"); // "Alex is a guest"💡 Default parameters allow you to initialize functions with values if no argument or `undefined` is passed.
// Example 3
// 3. Recursion
function factorial(n) {
if (n === 1) return 1; // Base case
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120💡 A function can call itself. This is called recursion. You must always have a **base case** to prevent an infinite loop (Stack Overflow).
Engine & Memory Architecture
Functions in Memory
1. Allocation:
- Function code is stored in the Heap as a complex object.
- The function name holds a pointer to that object.
2. Execution (The Call Stack):
- Every time a function is invoked, a new Execution Context (Stack Frame) is pushed onto the Stack.
- This frame holds the function's arguments and local variables.
- When the function returns, the frame is popped off, and memory for local variables is freed.
3. Stack Overflow:
- If too many functions are called (e.g., deep recursion without a base case), the Stack runs out of memory, causing a "Maximum call stack size exceeded" error.