Pure functions and side effects in JavaScript
What is a Pure Function?
A pure function is a function that:
- Given the same inputs, always returns the same output
- 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 Effect | Example |
|---|---|
| Modifying a global variable | counter++ |
| Mutating input arguments | array.push(item) |
| DOM manipulation | document.getElementById() |
| API calls | fetch(), XMLHttpRequest |
| Console output | console.log() |
| Writing to files | fs.writeFile() |
| Setting timers | setTimeout() |
| Modifying localStorage | localStorage.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
| Benefit | Description |
|---|---|
| Predictable | Same input β same output, always |
| Testable | No mocking needed, just test input/output |
| Cacheable | Results can be memoized |
| Parallelizable | No shared state, safe for concurrency |
| Debuggable | No 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.