IIFE and Recursion

Updated · 10 min read
hardES2026javascriptrecursioniifecall-stackinterview

This lesson covers two techniques built on functions calling functions. An IIFE (Immediately Invoked Function Expression) is a function that runs as soon as it is defined, a pattern from before modules and block scope that you'll still meet in older code. Recursion is a function that calls itself to solve a problem by breaking it into smaller versions of the same problem. It is the natural way to handle nested data such as folders, menus, comment threads and JSON documents of unknown depth.

In One Minute

  • An IIFE is (function () { ... })(); or (() => { ... })();: define and call at once, creating a private scope.
  • IIFEs were used for private variables and the var loop bug; modules, let and blocks replace them today.
  • A recursive function calls itself; every recursive function needs a base case that stops, and a recursive case that moves toward it.
  • Recursion fits nested structures of unknown depth.
  • Each call uses stack space; very deep recursion throws RangeError: Maximum call stack size exceeded. Use a loop or an explicit stack for huge inputs.

IIFE: Immediately Invoked Function Expressions

Syntax

syntax.js
(function () {
  // runs immediately
})();
 
(() => {
  // arrow version
})();
 
const result = (function (a, b) {
  return a + b;
})(2, 3);

The parentheses around the function make it an expression (a statement starting with function would be a declaration, which can't be called on the spot). The final () calls it.

Example

iife.js▶ Try it
const counter = (function () {
  let count = 0;
  return {
    next: () => ++count,
    reset: () => { count = 0; },
  };
})();
 
console.log(counter.next(), counter.next());
counter.reset();
console.log(counter.next());
console.log(typeof count);
Output
1 2
1
undefined

Explanation: the IIFE runs once, creating a private count and returning an object whose methods close over it. Nothing outside can reach count. This is the classic module pattern: before ES modules (2015), it was the main way to avoid global variables in browser scripts.

Why IIFEs Were Used, and What Replaced Them

IIFE used forModern replacement
Private variables, avoiding globalsES modules (top-level declarations are private to the file)
A new scope per loop round (var bug)let in the loop
A temporary scope for a few variablesA block { ... } with let/const
Running async code at the top levelTop-level await in modules, or (async () => { ... })()
Initialization that runs onceModule top-level code, or class static blocks

The async IIFE is still common in scripts that aren't modules:

async-iife.js▶ Try it
(async () => {
  const wait = (ms) => new Promise((r) => setTimeout(r, ms));
  await wait(10);
  console.log("Loaded after an await, inside an async IIFE");
})();
console.log("This line runs first");
Output
This line runs first
Loaded after an await, inside an async IIFE

Recursion

A function is recursive when it calls itself. To solve a problem recursively, you describe it in terms of a smaller version of the same problem:

  1. Base case: an input simple enough to answer directly, with no further calls.
  2. Recursive case: an input that is broken into a smaller piece, handled by calling the function again, and combined with the current step.
factorial.js▶ Try it
function factorial(n) {
  if (n <= 1) return 1;            // base case
  return n * factorial(n - 1);     // recursive case: a smaller problem
}
 
console.log(factorial(1), factorial(5), factorial(10));
Output
1 120 3628800

Explanation: factorial(5) is 5 * factorial(4), which is 5 * 4 * factorial(3), and so on until factorial(1) returns 1 directly. Then the multiplications finish on the way back up: 1, 2, 6, 24, 120.

Watching the Call Stack

trace.js▶ Try it
function countdown(n, depth = 0) {
  const indent = "  ".repeat(depth);
  if (n === 0) {
    console.log(`${indent}countdown(0): base case`);
    return;
  }
  console.log(`${indent}countdown(${n}) calls countdown(${n - 1})`);
  countdown(n - 1, depth + 1);
  console.log(`${indent}countdown(${n}) returns`);
}
countdown(3);
Output
countdown(3) calls countdown(2)
  countdown(2) calls countdown(1)
    countdown(1) calls countdown(0)
      countdown(0): base case
    countdown(1) returns
  countdown(2) returns
countdown(3) returns

Each call waits on the call stack until the call it made returns. The stack grows to depth 4, then unwinds.

Recursion for Nested Data

Recursion is at its best when the data itself is recursive: a folder contains folders, a menu contains submenus, a comment has replies. A loop can't easily handle unknown depth; recursion handles it naturally:

nested.js▶ Try it
const feeTree = {
  name: "All fees",
  children: [
    { name: "Tuition", amount: 400 },
    {
      name: "Supplies",
      children: [
        { name: "Books", amount: 85 },
        { name: "Lab kit", amount: 45 },
        { name: "Art", children: [{ name: "Paints", amount: 20 }] },
      ],
    },
  ],
};
 
function total(node) {
  if (!node.children) return node.amount;
  return node.children.reduce((sum, child) => sum + total(child), 0);
}
 
function outline(node, depth = 0) {
  const line = `${"  ".repeat(depth)}${node.name}: $${total(node)}`;
  return [line, ...(node.children ?? []).flatMap((c) => outline(c, depth + 1))];
}
 
console.log(total(feeTree));
console.log(outline(feeTree).join("\n"));
Output
550
All fees: $550
  Tuition: $400
  Supplies: $150
    Books: $85
    Lab kit: $45
    Art: $20
      Paints: $20

The base case is a leaf (no children). The recursive case sums the totals of the children, each computed by the same function. The code doesn't need to know how deep the tree goes.

Flattening and Deep Copies

flatten.js▶ Try it
function flatten(value) {
  return Array.isArray(value) ? value.flatMap(flatten) : [value];
}
console.log(flatten([1, [2, [3, [4, [5]]]], 6]));
 
function deepFreeze(obj) {
  for (const value of Object.values(obj)) {
    if (value && typeof value === "object") deepFreeze(value);
  }
  return Object.freeze(obj);
}
const settings = deepFreeze({ currency: "USD", limits: { late: { cap: 30 } } });
console.log(Object.isFrozen(settings.limits.late));
Output
[1, 2, 3, 4, 5, 6]
true

Stack Overflow

Every call takes a frame on the call stack, and the stack has a limited size (around 10,000 frames in V8, depending on frame size). Recursion that is too deep, or never stops, throws a RangeError:

overflow.js▶ Try it
function sumTo(n) {
  return n === 0 ? 0 : n + sumTo(n - 1);
}
 
console.log(sumTo(1000));
try {
  sumTo(1_000_000);
} catch (err) {
  console.log(err.name + ": " + err.message);
}
Output
500500
RangeError: Maximum call stack size exceeded

ES2015 specified proper tail calls, which would let some recursive functions run without growing the stack, but V8 (Chrome, Node.js) and SpiderMonkey (Firefox) don't implement them; only Safari's JavaScriptCore does. Don't rely on tail calls in JavaScript.

Converting Recursion to Iteration

For inputs that may be very deep, rewrite the recursion as a loop with an explicit stack (an array you push to and pop from):

iterative.js▶ Try it
function totalIterative(root) {
  let sum = 0;
  const stack = [root];
  while (stack.length > 0) {
    const node = stack.pop();
    if (node.children) stack.push(...node.children);
    else sum += node.amount;
  }
  return sum;
}
 
let deep = { amount: 1 };
for (let i = 0; i < 100_000; i++) deep = { children: [deep] };
console.log(totalIterative(deep));
Output
1

The tree is 100,000 levels deep, which would overflow the call stack with the recursive version, but the array-based stack grows on the heap, which has far more room.

Memoizing Recursive Functions

Some recursive functions recompute the same subproblems many times. The classic example is Fibonacci, where fib(n) calls fib(n - 1) and fib(n - 2), which call overlapping smaller values. Caching results (memoization) turns exponential work into linear work:

memo.js▶ Try it
let calls = 0;
function fibSlow(n) {
  calls++;
  return n < 2 ? n : fibSlow(n - 1) + fibSlow(n - 2);
}
console.log(fibSlow(25), "calls:", calls);
 
const cache = new Map();
let fastCalls = 0;
function fib(n) {
  fastCalls++;
  if (n < 2) return n;
  if (cache.has(n)) return cache.get(n);
  const result = fib(n - 1) + fib(n - 2);
  cache.set(n, result);
  return result;
}
console.log(fib(25), "calls:", fastCalls);
Output
75025 calls: 242785
75025 calls: 49

In Practice

The Fee Tracker's settings arrive as nested JSON from a server. A recursive function finds every amount anywhere in the structure and validates it, reporting the path to each bad value:

validate-tree.js▶ Try it
function findBadAmounts(value, path = "settings") {
  if (Array.isArray(value)) {
    return value.flatMap((item, i) => findBadAmounts(item, `${path}[${i}]`));
  }
  if (value && typeof value === "object") {
    return Object.entries(value).flatMap(([key, child]) => findBadAmounts(child, `${path}.${key}`));
  }
  const isAmountKey = /amount|fee|cap$/i.test(path);
  return isAmountKey && !(Number.isFinite(value) && value >= 0) ? [`${path} = ${JSON.stringify(value)}`] : [];
}
 
const settings = {
  lateFee: { perDay: 2, cap: 30 },
  grades: [{ grade: 9, fee: 400 }, { grade: 10, fee: "415" }, { grade: 11, fee: -1 }],
};
console.log(findBadAmounts(settings));
Output
['settings.grades[1].fee = "415"', 'settings.grades[2].fee = -1']

Common Mistakes

Missing or unreachable base case. The function recurses until the stack overflows. Check that every path either returns directly or moves toward the base case.

Recursing on untrusted or huge input. Deeply nested data can overflow the stack. Limit depth or use an explicit stack.

Recomputing overlapping subproblems. Memoize when the same arguments repeat.

Forgetting the semicolon before an IIFE. The previous line may be called as a function.

Interview Corner

What is an IIFE and why was it used?

An Immediately Invoked Function Expression runs as soon as it's defined: (function () { ... })(). It created a private function scope to avoid polluting globals, implement the module pattern, and capture per-iteration values with var. ES modules, block-scoped let/const, and top-level await replace most uses.

What are the parts of a recursive function, and what causes a stack overflow?

A base case that returns without recursing, and a recursive case that calls the function on a smaller input and combines results. Each call adds a stack frame; missing base cases or very deep recursion exhaust the stack and throw RangeError: Maximum call stack size exceeded. V8 doesn't implement tail-call optimization, so deep recursion should be converted to iteration.

Write a recursive deepCount(obj) that counts all primitive values in nested objects and arrays.

Show solution
deep-count.js▶ Try it
function deepCount(value) {
  if (value === null || typeof value !== "object") return 1;
  return Object.values(value).reduce((sum, v) => sum + deepCount(v), 0);
}
console.log(deepCount({ a: 1, b: [2, 3, { c: 4 }], d: { e: { f: 5 } } }));
Output
5

Practice

Challenge: Write a recursive findStudent(node, name) that searches a tree of classes (each node has students and optional subgroups) and returns the path of group names where the student is found, or null.

Show solution
find-student.js▶ Try it
const school = {
  name: "School",
  students: [],
  subgroups: [
    { name: "Grade 9", students: ["Navika"], subgroups: [] },
    { name: "Grade 11", students: [], subgroups: [{ name: "Robotics", students: ["Srihitha", "Advitha"] }] },
  ],
};
 
function findStudent(node, name, path = []) {
  const here = [...path, node.name];
  if (node.students.includes(name)) return here;
  for (const group of node.subgroups ?? []) {
    const found = findStudent(group, name, here);
    if (found) return found;
  }
  return null;
}
 
console.log(findStudent(school, "Advitha")?.join(" > "));
console.log(findStudent(school, "Zoe"));
Output
School > Grade 11 > Robotics
null

Quick check: IIFE and recursion

3 questions
1What does (function () { return 5; })() evaluate to?
2What must every recursive function have?
3What happens when recursion is too deep in Node.js?

Key Takeaways

PatternCode
IIFE(() => { ... })();
Async IIFE(async () => { await ...; })();
Recursionif (base) return x; return combine(f(smaller))
Tree walknode.children?.reduce((s, c) => s + f(c), 0)
Explicit stackwhile (stack.length) { const n = stack.pop(); ... }

Was this tutorial helpful?

Lesson 95 of 139