Log In

Don't have an account? Sign up now

Lost Password?

Sign Up

Prev Next

Module 5: Functions & The Execution Stack

1. Function Declarations vs. Expressions

There are two primary ways to define a function, and they behave differently during the Memory Creation Phase (Module 1).

A. Function Declaration

These are hoisted completely. You can call them before they appear in the code.

JavaScript

greet(); // "Hello!" (Works!)

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

B. Function Expression

The function is stored in a variable. These are not hoisted.

JavaScript

// sayHi(); // Error: sayHi is not a function

var sayHi = function() {
    console.log("Hi!");
};

2. Arrow Functions (ES6)

Arrow functions provide a shorter syntax and have a unique behavior regarding the this keyword (which we will cover in Module 7).

  • Syntax: (param) => { code }
  • Implicit Return: If the function is one line, you can omit return and the curly braces.

JavaScript

// Traditional
const add = function(a, b) { return a + b; };

// Arrow
const addArrow = (a, b) => a + b; 

3. Parameters vs. Arguments

  • Parameters: The placeholders defined in the function signature (e.g., a, b).
  • Arguments: The actual values passed when calling the function (e.g., 5, 10).

Advanced Parameter Handling:

  1. Default Parameters: Give a value if none is provided. function welcome(name = "Guest") { ... }
  2. Rest Parameter (...args): Collects multiple arguments into a single array.JavaScriptfunction sumAll(...numbers) { return numbers.reduce((acc, curr) => acc + curr, 0); }

4. Anonymous Functions & IIFE

  • Anonymous Function: A function without a name. Used often as “callbacks.”
  • IIFE (Immediately Invoked Function Expression): A function that runs as soon as it is defined. Used to create private scope.

JavaScript

(function() {
    console.log("I run immediately!");
})();

5. Higher-Order Functions (HOF)

A function that either takes a function as an argument or returns a function. This is the foundation of functional programming in JS.

JavaScript

function operate(a, b, operation) {
    return operation(a, b);
}

const multiply = (x, y) => x * y;
console.log(operate(5, 4, multiply)); // 20

6. The Execution Stack (Call Stack)

When a function is called, the JS engine creates a new Function Execution Context and pushes it onto the Call Stack.

How it works:

  1. Global Execution Context is always at the bottom.
  2. Each function call adds a “frame” to the top.
  3. When a function returns, its frame is “popped” off, and the engine goes back to where it left off.

Technical Code Example: The Power of HOF

This example shows how functions can return other functions (the basis for “Factories”).

JavaScript

function createMultiplier(multiplier) {
    // This is a Higher-Order Function returning an anonymous function
    return function(number) {
        return number * multiplier;
    };
}

const double = createMultiplier(2);
const triple = createMultiplier(3);

console.log(double(10)); // 20
console.log(triple(10)); // 30

In Simple Words

1. Introduction to Functions

What is a Function?

A function is a reusable block of code designed to perform a specific task.

Example (conceptual):

calculateSalary()
validateUser()
printReport()

Why Functions Are Important

  • Code reusability
  • Modular programming
  • Better readability
  • Easier debugging & testing
  • Reduces code duplication

2. Function Anatomy

A function generally consists of:

  1. Function Name
  2. Parameters (Inputs)
  3. Function Body
  4. Return Statement
  5. Return Type

Example structure:

returnType functionName(parameters) {
   statements
   return value
}

3. Function Declaration vs Definition

Function Declaration

  • Tells the compiler about function name and signature
  • No implementation
int add(int, int)

Function Definition

  • Actual implementation of the function
int add(int a, int b) {
   return a + b
}

4. Function Calling

How a Function Call Works

  1. Control jumps to function
  2. Parameters are passed
  3. Function executes
  4. Return value sent back
  5. Control resumes after call

5. Parameters & Arguments

Parameters

Variables defined in function definition.

Arguments

Actual values passed during function call.


Types of Parameter Passing

Pass by Value

  • Copy of value passed
  • Original data unchanged

Pass by Reference

  • Memory address passed
  • Original data can change

6. Return Types

  • void → returns nothing
  • Single value return
  • Multiple values (via objects/tuples/structures)

7. Scope of Variables in Functions

Variable TypeScope
LocalInside function
GlobalEntire program
StaticRetains value across calls

8. Recursion

What is Recursion?

A function calling itself to solve a problem.


Components of Recursion

  1. Base condition
  2. Recursive call

Example:

factorial(n) = n * factorial(n-1)

Advantages

  • Cleaner code
  • Natural fit for problems like trees, graphs

Disadvantages

  • More memory usage
  • Risk of stack overflow

9. Introduction to the Execution Stack

What is the Execution Stack?

A stack data structure that stores:

  • Function calls
  • Local variables
  • Parameters
  • Return addresses

Also called:

  • Call Stack
  • Runtime Stack

10. Stack Frame (Activation Record)

Each function call creates a stack frame containing:

  • Function parameters
  • Local variables
  • Return address
  • Saved registers

11. How the Call Stack Works

Example:

main()
 └── funcA()
      └── funcB()

Execution order:

  1. main() pushed
  2. funcA() pushed
  3. funcB() pushed
  4. funcB() popped
  5. funcA() popped
  6. main() popped

12. Stack Memory Characteristics

  • Follows LIFO
  • Very fast access
  • Automatically managed
  • Limited size

13. Stack Overflow

What is Stack Overflow?

Occurs when:

  • Too many function calls
  • Infinite recursion
  • Large local variables

Result:

  • Program crash

14. Functions vs Methods

FeatureFunctionMethod
Belongs toStandaloneClass/Object
OOP conceptOptionalMandatory
Access dataLimitedObject data

15. Built-in vs User-Defined Functions

Built-in Functions

Provided by language.
Example:

  • print()
  • len()
  • sqrt()

User-Defined Functions

Created by programmers.


16. Function Overloading

What is Function Overloading?

Multiple functions with same name but different parameters.

Example:

add(int, int)
add(float, float)

17. Default & Named Arguments

(Language-dependent)

  • Default parameters
  • Keyword/named arguments
  • Improve flexibility

18. Inline Functions

Inline Function

Compiler replaces function call with function body.

Advantages:

  • Faster execution

Disadvantages:

  • Larger code size

19. Lambda / Anonymous Functions

Definition

Functions without names.

Used for:

  • Short operations
  • Callbacks
  • Functional programming

20. Execution Stack vs Heap

FeatureStackHeap
StoresFunction callsObjects
SpeedFastSlower
SizeLimitedLarge
ManagementAutomaticManual / GC

Leave a Comment

    🚀 Join Common Jobs Pro — Referrals & Profile Visibility Join Now ×
    🔥