JS Built-ins
Closuresintermediate

Closures β€” Nested closures

πŸ“– Usage Example
const outer = (a) => (b) => (c) => a + b + c
const step1 = outer(10)
const step2 = step1(5)
step2(3)  // β†’ 18

Each nesting level creates a new closure that accumulates captured variables from all outer scopes, enabling composable step-by-step function application.

Multiple Levels of Nesting

A function can close over variables from multiple outer scopes, creating nested closures.

Challenge: Create a function that returns a function, which in turn returns another function. Each level should capture and use variables from its outer scope.

Example:

const outer = (a) => {
  return (b) => {
    return (c) => a + b + c
  }
}
outer(1)(2)(3)  // 6
πŸ’‘ Hints (3)
  • β€’ Each function returns another function
  • β€’ Inner functions have access to all outer scopes
  • β€’ This pattern enables partial application