๐Ÿš€ LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
๐ŸŽ“ COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
JS MASTER CLASS /// MASTER THE ENGINE /// BUILD LOGIC /// ASYNC PATTERNS /// JS MASTER CLASS /// MASTER THE ENGINE ///

Pure Functions | JavaScript Tutorial - In-Depth Guide

Understand what makes a function pure, why side effects and pure functions are opposites, and how to identify and refactor impure functions in real code.

โšก Total XP: 0|๐Ÿ’ป javascript XP: 0

Skill Matrix

UNLOCK NODES BY LEARNING NEW TAGS.

System Hub

Core logic.

Quick Quiz //

Does calling `console.log()` inside a function make that function impure?


๐Ÿš€ LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
๐ŸŽ“ COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.

A pure function always returns the same output for the same input and causes no observable side effects. Pure functions are the easiest code in any codebase to test, reason about, and safely run in parallel or cache.

1Pure Functions | JavaScript Tutorial - In-Depth Guide Part 1

A pure function has two properties: given the same input, it always returns the same output, and it produces no side effects.

โœ•
โ€”
+
function add(a, b) {
  return a + b; // always same output, no side effects
}
localhost:3000
๐Ÿงช

Two Properties

2Pure Functions | JavaScript Tutorial - In-Depth Guide Part 2

A side effect is anything a function does besides computing its return value: mutating an argument, changing a global variable, logging, or making a network request.

โœ•
โ€”
+
let total = 0;
function addToTotal(n) {
  total += n; // side effect: mutates outer variable
}
localhost:3000

What Is a Side Effect?

3Pure Functions | JavaScript Tutorial - In-Depth Guide Part 3

Mutating an argument passed into a function is a side effect too, even if the function also returns a value.

โœ•
โ€”
+
function addItem(cart, item) {
  cart.items.push(item); // mutates caller's cart!
  return cart;
}
localhost:3000

Mutating Arguments

4Pure Functions | JavaScript Tutorial - In-Depth Guide Part 4

The pure version of the same function returns a new object instead of mutating the one it received.

โœ•
โ€”
+
function addItem(cart, item) {
  return { ...cart, items: [...cart.items, item] };
}
localhost:3000

The Pure Version

5Pure Functions | JavaScript Tutorial - In-Depth Guide Part 5

Pure functions are trivially easy to unit test, safely cacheable via memoization, and safe to run concurrently since they touch no shared state.

โœ•
โ€”
+
test('addItem returns a new cart', () => {
  const cart = { items: [] };
  const next = addItem(cart, 'apple');
  expect(cart.items).toEqual([]); // untouched
  expect(next.items).toEqual(['apple']);
});
localhost:3000

Why It Matters

6Step-by-Step Breakdown

A pure function has two properties: given the same input, it always returns the same output, and it produces no side effects.

A side effect is anything a function does besides computing its return value: mutating an argument, changing a global variable, logging, or making a network request.

Checkpoint: Does calling console.log() inside a function make that function impure?

  • โ†’Yes, logging is an observable side effect
  • โ†’No, console.log does not affect the return value

Mutating an argument passed into a function is a side effect too, even if the function also returns a value.

The pure version of the same function returns a new object instead of mutating the one it received.

Checkpoint: In the pure version of addItem, does the original cart object passed in ever get modified?

  • โ†’Yes, the spread operator still mutates it
  • โ†’No, a completely new object is returned instead

Pure functions are trivially easy to unit test, safely cacheable via memoization, and safe to run concurrently since they touch no shared state.

Next, we'll explore 'Function Composition'.

Level Up ๐Ÿš€

Advanced cheat sheets, SEO tricks, and interview prep for this topic.

Browser Support

ChromeSupported

Fully supported.

FirefoxSupported

Fully supported.

SafariSupported

Fully supported.

EdgeSupported

Fully supported.

Accessibility (A11y)

1Pure Rendering Logic Produces More Predictable Accessible Output

When the function that computes ARIA attribute values from state is pure, the same application state always renders the same accessibility tree, making assistive technology behavior consistent and easier to test automatically.

SEO Implications

  • 1

    Pure Rendering Functions Reduce Server-Rendering Inconsistencies

    Server-side rendering that relies on pure functions to compute page markup from data avoids subtle hydration mismatches caused by hidden state or side effects, which can otherwise produce inconsistent HTML seen by crawlers versus users.

Best Practices

Isolate Side Effects at the Edges of Your Application

Keep core business logic (calculations, transformations) pure, and push I/O, DOM updates, and logging to a thin outer layer โ€” this maximizes the amount of easily testable code.

Never Mutate Function Arguments

Treat every argument as read-only inside a function body; return a new value instead of mutating in place, so callers are never surprised by changes to objects they still hold a reference to.

Frequent Bugs

THE BUG

A function that appears to just 'calculate' something actually mutates a shared array or object passed as an argument, causing distant, hard-to-trace bugs elsewhere in the app.

THE FIX

Audit functions that take objects/arrays as arguments for any mutation methods (push, splice, direct property assignment) and replace them with non-mutating equivalents that return new data.

THE BUG

Relying on `Date.now()` or `Math.random()` inside a function that is otherwise treated as pure, then being confused when tests produce different results each run.

THE FIX

Recognize that any function reading external, changing state (the clock, randomness, global variables) is inherently impure โ€” inject these as parameters instead so tests can supply fixed values.

Real-World Examples

Pure Reducer Functions in State Management

A state management library required every state-update function to be pure so it could support features like time-travel debugging and undo/redo.

function cartReducer(state, action) {
  switch (action.type) {
    case 'ADD_ITEM':
      return { ...state, items: [...state.items, action.item] };
    default:
      return state;
  }
}

Interview Prep

?Frequently Asked Questions

Pascual Vila

Pascual Vila

Frontend Instructor // Code Syllabus

Common Pitfalls & Errors

The Error //

Mutating a function argument by mistake

function rename(user, name) { return { ...user, name }; // does not touch the original user }

The Solution //

Copy the argument (spread, slice, structuredClone) before making any changes, and return the modified copy instead.

Lesson Glossary

[01]Pure Function

A function that always returns the same output for the same input and has no side effects.

Code Preview
(a,b) => a+b

[02]Side Effect

Any observable change a function makes outside of its return value.

Code Preview
console.log()

[03]Referential Transparency

The property that a function call can be replaced by its result without changing the program's behavior.

Code Preview
f(x) === f(x)

[04]Idempotence

A related property where calling an operation multiple times has the same effect as calling it once.

Code Preview
setState(x)

[05]Immutable Update

Producing a new data structure instead of mutating an existing one.

Code Preview
{ ...obj }

Continue Learning