In JavaScript, a pure function is a function that always produces the same output given the same input and has no side effects.

💡 Key Characteristics of Pure Functions
- Deterministic: Always returns the same result for the same arguments.
- No Side Effects: Does not modify external state or data.
Pure functions are predictable, easier to test, and enable functional programming patterns.
| Pure Function | Impure Function |
|---|---|
| Returns consistent output for same inputs | Output may vary despite same inputs |
| No modification of external variables | Modifies external state or variables |
| No side effects (e.g. no I/O, no DOM changes) | Has side effects like API calls, DOM manipulation |
| Easier to test and debug | Harder to test due to hidden dependencies |
📌 Deep Dive: Example of a Pure Function
function add(a, b) {
return a + b;
}
This function always returns the sum of a and b without changing anything outside itself.
📌 Deep Dive: Example of an Impure Function
let count = 0;
function increment() {
count++;
return count;
}
increment() // 2
This function changes the external variable count, so it is not pure.
⚠️ Why Avoid Side Effects?
Side effects make functions unpredictable and harder to debug because changes happen outside the function scope.
Pure functions help keep code more reliable and easier to reason about, especially in complex applications.
💡 Summary
- Pure functions return values based only on input parameters.
- They never modify variables or data outside their scope.
- They make your code more testable and maintainable.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which of the following is a characteristic of a pure function?
Question 2 of 2
Why are pure functions easier to test?
Loading results...