Skip to main content
Practice Problems

Pure functions and side effects in JavaScript

What is a Pure Function?

A pure function is a function that:

  1. Given the same inputs, always returns the same output
  2. Has no side effects β€” doesn't modify anything outside its scope

Pure Function Examples

javascript
// βœ… Pure β€” same input always gives same output function add(a, b) { return a + b; } // βœ… Pure β€” no external dependencies, no mutations function formatName(first, last) { return `${first} ${last}`; } // βœ… Pure β€” creates new array, doesn't modify original function double(numbers) { return numbers.map(n => n * 2); }

Impure Function Examples

javascript
// ❌ Impure β€” depends on external state let discount = 0.1; function getPrice(price) { return price * (1 - discount); // Result changes if discount changes } // ❌ Impure β€” modifies external state (side effect) let total = 0; function addToTotal(amount) { total += amount; // Mutates external variable return total; } // ❌ Impure β€” random output function getRandomId() { return Math.random(); } // ❌ Impure β€” mutates input function sortArray(arr) { return arr.sort(); // Modifies the original array! }

What are Side Effects?

A side effect is any operation that modifies state outside the function's scope:

Side EffectExample
Modifying a global variablecounter++
Mutating input argumentsarray.push(item)
DOM manipulationdocument.getElementById()
API callsfetch(), XMLHttpRequest
Console outputconsole.log()
Writing to filesfs.writeFile()
Setting timerssetTimeout()
Modifying localStoragelocalStorage.setItem()

Making Functions Pure

javascript
// ❌ Impure β€” mutates input function addItem(cart, item) { cart.push(item); return cart; } // βœ… Pure β€” returns new array function addItem(cart, item) { return [...cart, item]; } // ❌ Impure β€” mutates object function updateAge(user, age) { user.age = age; return user; } // βœ… Pure β€” returns new object function updateAge(user, age) { return { ...user, age }; }

Why Pure Functions Matter

BenefitDescription
PredictableSame input β†’ same output, always
TestableNo mocking needed, just test input/output
CacheableResults can be memoized
ParallelizableNo shared state, safe for concurrency
DebuggableNo hidden state changes to track

Pure Functions in React

javascript
// βœ… Pure component β€” same props give same render function UserCard({ name, avatar }) { return ( <div> <img src={avatar} alt={name} /> <h2>{name}</h2> </div> ); } // Side effects go in useEffect function UserProfile({ userId }) { const [user, setUser] = useState(null); useEffect(() => { fetchUser(userId).then(setUser); // Side effect isolated }, [userId]); return <UserCard name={user?.name} avatar={user?.avatar} />; }

Important:

Keep functions pure whenever possible. Isolate side effects into dedicated functions or hooks (useEffect in React). This makes code more predictable, testable, and easier to reason about. Most functional programming patterns are built on pure functions.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems