Skip to content
Concept 31 // Module 04: Functions & Execution Model

Function Declarations vs Function Expressions

Module 04: Functions & Execution Model•Concept 31 of 100• 5 min read

Function Declarations vs Function Expressions

Functions are reusable blocks of code. In JavaScript, functions are **first-class citizens**, meaning they can be stored in variables, passed as arguments, and returned from other functions.

The Core Concept

Syntax Reference
// 1. Function Declaration
function greet(name) {
  return "Hello " + name;
}

// 2. Function Expression
const sum = function(a, b) {
  return a + b;
};

// 3. Arrow Function
const square = (x) => x * x;

// 4. Calling a function
const val = sum(5, 10);

Live Interactive Studio

Function declarations are moved to the top of their scope during the creation phase. Expressions are not, behaving like any other variable.
JavaScript Editor
Loading...
Console Output
Waiting for output...

Key Code Patterns in Action

01

Declarations are Hoisted

// 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.
02

Default Parameters

// 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.
03

Recursion

// 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).
04

1. Core Usage: Function Declarations vs Function Expressions

// Core syntax and usage for Function Declarations vs Function Expressions
const feature = 'function-declarations-vs-function-expressions';
console.log('Concept 31:', feature);
console.log('Active:', true);
Illustrates the fundamental invocation and syntax structure for Function Declarations vs Function Expressions.
05

2. Defensive Handling & Edge Case

// Edge-case defensive handling
function handleSafe(input) {
  if (input === null || input === undefined) return 'safe-fallback';
  return String(input).trim();
}
console.log(handleSafe('function-declarations-vs-function-expressions'));
console.log(handleSafe(null));
Shows how to write defensive, safe JavaScript code that handles nullish or unexpected inputs when working with Function Declarations vs Function Expressions.
06

3. Clean Architecture & Production Pattern

// Production-grade pattern for Function Declarations vs Function Expressions
const settings = Object.freeze({
  id: 'function-declarations-vs-function-expressions',
  ready: true,
  timestamp: Date.now()
});
console.log('Settings initialized:', settings.id, settings.ready);
Demonstrates clean, immutable production code avoiding unintended state mutations.

Real-World Engineering Takeaways

DRY (Don't Repeat Yourself): Move repeated code into a function.
Encapsulation: Hide logic and only expose the result.
Event Listeners: Passing a function to be called when a button is clicked.
Asynchronous Code: Passing functions (callbacks) to be executed after data is fetched.

Under the Hood: Engine & Memory Mechanics

How JavaScript Executes This
### **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.

Quick Knowledge Check

Test your understanding on these 10 questions (one by one):

Score: 0 / 10
Question 1 of 10 • Core Purpose & Mental Model

What is the core purpose of Function Declarations vs Function Expressions in JavaScript?

// Concept 31: Function Declarations vs Function Expressions
// Understanding the core mental model
1 / 10