JavaScript Tutorial ✦
Pure Functions
What is a Pure Function?
Pure functions are the functions that follow 2 main rules:
-
It will give the same output for the same arguments always.
Example:function test(a, b) { return a + b; // 8 is the answer always when we pass 5 and 3 } test(5, 3); // always returns 8
-
It will not make any side effects.
That means:- It will not modify any external variables (variables that are outside the function).
- It will not access network (like calling an API).
- It will not access file systems.
- It will not manipulate the DOM.
Example of a function not pure:
let count = 0; function test() { count++; // modifies external variable return count; }
Example of a pure function:
function test(count) { return count; // does not change anything outside }
How Pure Functions Become Useful:
- ✅ Predictable behavior – If you give the same input, you always get the same output. No surprises.
- ✅ Helps in functional programming – Because they are independent and don’t rely on anything outside.
- ✅ Easy to debug – Since there are no side effects, you don’t need to worry about other parts of code affecting it.
const add = (a, b) => a + b; // Pure function
let counter = 0;
const increment = () => counter++; // not a pure function