Pure Functions
A pure function is one that always returns the same output for the same inputs and causes no side effects, meaning it never changes anything outside itself or depends on external state.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
💡 Running Code Locally: While this online editor runs real JavaScript, some advanced examples may have limitations. For the best experience:
- Download Node.js to run JavaScript on your computer
- Use your browser's Developer Console (Press F12) to test code snippets
- Create a .html file with <script> tags and open it in your browser
Master the principles that drive reliable, predictable, and scalable JavaScript applications
What You'll Learn in This Lesson
Pure Functions — The Foundation of Predictable JavaScript
A pure function is a function that, for the same input, always returns the same output and causes no side effects.
- Same input → same output
- No external state modification
Example: Pure vs Impure
Why Pure Functions Matter
Pure functions reduce bugs because they are self-contained. When debugging, you examine inputs and outputs, not the entire program's state.
Why Pure Functions Improve Performance & Testing
Pure functions enable powerful optimizations that JavaScript engines can automatically apply:
- • Memoization (automatic caching)
- • Parallel processing
- • Predictable code paths
- • Zero hidden dependencies
- • Automatic optimizations in JS engines
Memoization Example
Immutability — Avoiding Accidental State Corruption
Immutability means state never changes directly; new state is returned instead.
Arrays: Mutable vs Immutable
Objects: Mutable vs Immutable
Accidental Mutation — The #1 Cause of Hidden Bugs
Even experienced developers make mistakes by accidentally mutating data:
❌ Common Mistake
✅ Better Version
Side Effects — Necessary but Dangerous
A side effect is any interaction with the outside world:
- • Modifying external variables
- • Updating the DOM
- • Fetching data
- • Writing files
- • Changing global state
- • Generating random numbers
- • Date/time access
- • Logging to console
Controlled Side Effects
Pure Core + Isolated Effects = Scalable Architecture
Modern design philosophy splits code into three layers:
- Pure logic layer — calculations, transformations, business rules
- Side-effect layer — API calls, storage, DOM updates
- Coordinator layer — injects values and orchestrates
Architecture Benefit
This isolates risk and keeps the pure core clean. Testing becomes easier because the pure logic has no dependencies on external state.
Hidden Side Effects That Developers Forget
Important
Side effects are unavoidable — but detecting them means you can isolate them.
Accidental Mutation with Arrays & Objects
Many built-in methods mutate data. Know which ones!
❌ Mutating Array Methods
✅ Non-Mutating Methods
- toReversed()
Immutability in Nested Structures
Functional Composition with Pure Functions
Pure functions chain beautifully using functional composition:
Real-World Architecture Pattern
Professional engineers separate pure logic from side effects at architectural boundaries:
Key Takeaway
Pure functions, immutability, and controlled side effects aren't just "good practices" — they form the backbone of reliable, scalable, and bug-resistant JavaScript systems. Master these concepts to gain full control over application complexity, performance, and long-term maintainability.
Where These Patterns Appear in Real Life
Frontend Frameworks
- • React hooks & state
- • Redux reducers
- • Vue composition API
- • Svelte stores
Backend Systems
- • Express middleware
- • MongoDB query builders
- • GraphQL resolvers
- • API transformers
Data Processing
- • Functional pipelines
- • Data validation
- • ETL processes
- • Stream processing
Modern Tools
- • AI prompt pipelines
- • Event handler factories
- • Web scrapers
- • Game engines
Lesson Complete!
You've mastered pure functions, immutability, and controlled side effects — the backbone of reliable, scalable JavaScript. You now know how to write code that is predictable, testable, and bug-resistant.
Up next: Memory Management & Garbage Collection — learn how JavaScript manages memory automatically and how to avoid memory leaks in production apps.
📋 Quick Reference
Concept
Key Rule
Pure function
Same input → same output, no side effects
Immutability
Return new objects/arrays, never mutate
Side effect
Any interaction with outside world (DOM, API, logging)
Memoization
Cache pure function results for performance
Composition
pipe(...fns)(x) — chain pure functions
Practice quiz
What are the two rules of a pure function?
- Use const and return a value
- Be async and cache results
- Same input gives same output, and no external state modification
- Log to console and mutate inputs
Answer: Same input gives same output, and no external state modification. Pure functions return the same output for the same input and never modify external state.
What does immutability mean in this lesson?
- State never changes directly; new state is returned instead
- Variables are constant
- Objects are frozen forever
- Functions cannot be called twice
Answer: State never changes directly; new state is returned instead. Immutability means returning new objects/arrays rather than mutating existing state.
Which array method mutates the original array?
- map()
- filter()
- slice()
- push()
Answer: push(). push() mutates the original; map, filter, and slice return new arrays.
Why does copy.user.level = 2 also change the original when copy = { ...state }?
- Spread is broken
- A shallow copy still shares nested object references
- level is a getter
- Objects cannot be copied
Answer: A shallow copy still shares nested object references. Spread makes a shallow copy, so nested objects are shared by reference.
Which of these is a side effect?
- Fetching data or logging to the console
- Returning a + b
- Multiplying two numbers
- Declaring a const
Answer: Fetching data or logging to the console. Any interaction with the outside world (fetch, DOM, logging, randomness) is a side effect.
What is the output of the pipe transform: double, then square, then addTen applied to 5?
- 100
- 60
- 110
- 35
Answer: 110. 5*2=10, 10*10=100, 100+10=110.
Why is const tax = x => x * rate; (where rate is an outer variable) NOT pure?
- It uses an arrow function
- It depends on an external variable
- It returns a number
- It has too many arguments
Answer: It depends on an external variable. Depending on an external variable means the result can change without the input changing.
What does memoization do for a pure function?
- Mutates its arguments
- Runs it on another thread
- Makes it impure
- Caches results so repeated calls with the same input are fast
Answer: Caches results so repeated calls with the same input are fast. Memoization caches pure-function results, returning instantly on repeat inputs.
In the architecture pattern, which layer contains API calls and DOM updates?
- Pure logic layer
- Side-effect layer
- Coordinator layer
- Memoization layer
Answer: Side-effect layer. The side-effect layer handles API calls, storage, and DOM updates, kept separate from pure logic.
After const updated = addScore(player, 5) using the immutable version (spread), what is player.score (originally 10)?
- 15
- 5
- 10
- undefined
Answer: 10. The immutable version returns a new object, so the original player.score stays 10.