What Is a Pure Function?
One of the most important concepts in Functional Programming is the Pure Function.
A pure function does only two things:
- Receives inputs.
- Processes them and returns an output.
It does not modify anything outside the function, nor does it depend on external state.
In other words, given the same inputs, it will always produce the same output.
Example of a Pure Function
function add(a, b) { return a + b;}This is a pure function because it:
- Receives two values.
- Calculates their sum.
- Returns the result.
- Does not modify any external data.
Calling it like this:
add(5, 10);will always return:
15regardless of when or where it is called.
What Does return Do?
The return keyword sends a value back to the code that called the function.
return a + b;Once return is executed, the function immediately stops running and returns the specified value.
Any code written after return inside the function will not be executed.
Example of an Impure Function
Now consider this example:
let sum = 0;
function add(a, b) { sum = a + b; return a + b;}This is not a pure function.
Why?
Because it modifies a variable that exists outside the function.
sum = a + b;This is known as a side effect, because the function changes external state instead of simply returning a value.
Functional Programming encourages avoiding side effects whenever possible, making functions easier to test, reuse, and reason about.
Key Takeaways
- A Pure Function receives inputs and returns an output.
- It does not depend on or modify external variables.
- Given the same inputs, it always returns the same result.
returnsends a value back to the caller and ends the function.- A function that modifies external state is not a pure function.