# Immutability & Pure Functions

> The foundations of predictable code. Learn how to write safe, side-effect-free functions and avoid the nightmare of unintended data mutations.

Subject: JavaScript | Lesson 58 of 63 | 7 min read
Interactive lesson: https://codewithanimation.in/javascript/immutability-and-pure-functions
Previous: [Design Patterns: Module, Factory, Observer](https://codewithanimation.in/javascript/design-patterns.md) | Next: [Performance & Rendering](https://codewithanimation.in/javascript/performance-and-rendering.md)

## The Rules of Predictability

A **Pure Function** must satisfy two rules: 1) Given the exact same inputs, it will always return the exact same output. 2) It produces zero side effects (no DOM manipulation, no network calls, no modifying external variables).

**Immutability** means that once a piece of data is created, it cannot be changed. If you need to update it, you must create a brand new copy with the updated values.

## Preventing Spooky Action at a Distance

If you pass an object into a function, and that function silently mutates a property on the object, it affects the rest of your application. This leads to bugs that are incredibly difficult to track down.

By enforcing pure functions and immutable data, your code becomes highly testable, predictable, and safe for concurrent execution.

## Making Copies in JavaScript

JavaScript objects and arrays are mutable by default. To enforce immutability, you must use the spread operator (`...`) or array methods like `.map()` and `.filter()` which return *new* arrays rather than modifying the original.

```javascript
// Impure (Mutates original)
function addRole(user) {
  user.role = 'admin'; 
  return user;
}
```

```javascript
// Pure (Returns a new copy)
function addRole(user) {
  return { ...user, role: 'admin' };
}
```

## Common mistake: Deep Clones are Expensive

The spread operator (`...`) only creates a *shallow copy*. If your object has deeply nested objects, those nested objects are still passed by reference and can be mutated.

For deep immutability, you must use `structuredClone()`, but be warned: deep cloning large objects repeatedly can hurt performance.

## Tip: React Strict Mode

If you've ever wondered why React calls your render functions twice in development mode, this is why! React is intentionally testing your components to ensure they are **Pure Functions**. If your component mutates an external variable during render, the double-render will expose the bug immediately.

## Try it: Impure vs Pure Pipelines

Study the architecture diagram below. Notice how the Impure function reaches outside of its scope to modify a global variable, creating a dangerous side effect, while the Pure function is completely self-contained.

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

## Check yourself

### Question 1

Which of the following makes a function IMPURE?

- A. Updating a variable that was declared outside the function.
- B. Returning a new object using the spread operator.
- C. Accepting more than 3 arguments.

Correct answer: A

A pure function must not have side effects. Modifying a variable outside of its own scope is a classic side effect.

- Why not B: Incorrect. Returning a new object preserves immutability and keeps the function pure.
- Why not C: Incorrect. The number of arguments doesn't affect purity.

### Question 2

Why is `Array.prototype.push()` considered a mutating (impure) operation?

- A. Because it modifies the original array directly in memory.
- B. Because it creates a brand new array.
- C. Because it requires a callback function.

Correct answer: A

Methods like `.push()`, `.pop()`, and `.splice()` alter the original array. In functional programming, you should use `.concat()`, `.map()`, or the spread operator `[...arr, newItem]` to create a new array instead.

- Why not B: Incorrect. `.concat()` creates a new array, but `.push()` modifies the existing one.
- Why not C: Incorrect. `.push()` does not take a callback.

### Question 3

A function takes `x` and returns `x + Math.random()`. Is this a pure function?

- A. No, because passing the same input will result in different outputs.
- B. Yes, because it doesn't modify any external variables.
- C. Yes, because Math is a built-in object.

Correct answer: A

A pure function must be deterministic. If you pass `5` to it ten times, it must return the exact same answer ten times. `Math.random()` breaks predictability.

- Why not B: Incorrect. It satisfies the 'no side effects' rule, but fails the 'same input = same output' rule.
- Why not C: Incorrect. Math.random() inherently prevents a function from being deterministic.

## Remember this

- A **Pure Function** has two rules: Same input always equals same output, and ZERO side effects.
- Side effects include: mutating external variables, making HTTP requests, and modifying the DOM.
- **Immutability** dictates that data should not be changed after creation. You must create updated copies instead.
- Use the spread operator (`...`) or methods like `.map()` and `.filter()` to create shallow copies of objects and arrays.
- React components and Redux reducers strictly require pure functions and immutable data to operate correctly.
