# Memoization & Currying

> Two powerful functional programming techniques. Learn how to cache expensive function calls (Memoization) and break down complex functions into smaller, reusable pieces (Currying).

Subject: JavaScript | Lesson 56 of 63 | 7 min read
Interactive lesson: https://codewithanimation.in/javascript/memoization-and-currying
Previous: [Debounce & Throttle](https://codewithanimation.in/javascript/debounce-throttle.md) | Next: [Design Patterns: Module, Factory, Observer](https://codewithanimation.in/javascript/design-patterns.md)

## Optimization and Transformation

**Memoization** is a caching strategy. It allows a function to 'remember' its previous inputs and outputs. If it sees the same input again, it returns the cached answer instantly instead of recomputing it.

**Currying** is a structural transformation. It converts a function that takes multiple arguments (`f(a, b)`) into a sequence of functions that each take a single argument (`f(a)(b)`).

## Performance and Reusability

Use Memoization to speed up slow, CPU-heavy algorithms or redundant API calls. If a calculation takes 2 seconds to run, running it twice shouldn't take 4 seconds-it should take 2.001 seconds.

Use Currying to create highly reusable 'factory' functions. By currying a logging function `log(level)(message)`, you can easily create specialized versions like `const logError = log('ERROR')` and use it everywhere.

## Writing them in JavaScript

Both patterns rely heavily on **Closures** (functions returning functions and remembering their lexical scope).

**Memoization:**

```javascript
function memoize(fn) {
  const cache = {};
  return function(x) {
    if (cache[x]) return cache[x];
    const result = fn(x);
    cache[x] = result;
    return result;
  }
}
```

**Currying:**

```javascript
function multiply(a) {
  return function(b) {
    return a * b;
  }
}
// Or in ES6:
const multiply = a => b => a * b;
```

## Common mistake: The Limits of the Cache

A common pitfall with Memoization is memory exhaustion. If your function accepts a million different unique inputs, your `cache` object will grow endlessly until the browser crashes.

In production, use caching libraries (or LRU caches) that automatically delete the oldest or least-used entries to cap memory usage.

## Tip: React's useMemo

If you use React, you are already using memoization! The `useMemo()` hook caches the result of an expensive calculation, and `React.memo()` caches an entire component, preventing it from re-rendering unless its props change.

## Try it: The Cacher & The Curry

Explore both concepts below. In the Memoization panel, notice how the first calculation takes time, but subsequent identical calls are instantaneous. In the Currying panel, watch how passing one argument creates a brand new function waiting for the next.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/javascript/memoization-and-currying

## Check yourself

### Question 1

What is the primary benefit of Memoization?

- A. It prevents a function from re-calculating the same result for an input it has already seen.
- B. It reduces the amount of memory your application uses.
- C. It turns synchronous functions into asynchronous functions.

Correct answer: A

Memoization trades memory for speed. By storing the results in a cache, you skip the computation phase on subsequent calls.

- Why not B: Incorrect. Memoization actually *increases* memory usage because it stores previous answers in a cache object.
- Why not C: Incorrect. Memoization does not change whether a function is async or sync.

### Question 2

Which ES6 arrow function perfectly represents a curried `add(a, b)` function?

- A. const add = a => b => a + b;
- B. const add = (a, b) => a + b;
- C. const add = (a) => (a, b) => a + b;

Correct answer: A

A curried function returns another function. `a => b => a + b` means: taking `a`, return a function that takes `b`, which returns `a + b`.

- Why not B: Incorrect. This is a standard multi-argument function, not curried.
- Why not C: Incorrect. This syntax is invalid/redundant.

### Question 3

Why do both Memoization and Currying fundamentally rely on Closures?

- A. Because the inner functions must 'remember' data (like the cache object or the first argument) from the outer function's scope.
- B. Because closures make the code run on the GPU.
- C. Because `var` scoping is broken.

Correct answer: A

In Currying, the inner function remembers `a` when you pass `b`. In Memoization, the returned function remembers the `cache` object defined in its parent.

- Why not B: Incorrect. Closures do not affect hardware acceleration.
- Why not C: Incorrect. Closures are a fundamental feature of lexical scoping, not a bugfix.

## Remember this

- **Memoization** caches function results. If the same inputs are provided again, it returns the cached answer instantly.
- Memoization trades memory (storing the cache) for speed (skipping computation).
- **Currying** transforms a function of multiple arguments into a chain of single-argument functions: `f(a)(b)(c)`.
- Currying is excellent for creating specialized, reusable 'factory' functions from generic ones.
- Both patterns rely on **Closures** to remember state (the cache object, or the earlier arguments) across executions.
