What Is a Pure Function?
A pure function is one of the most important concepts to learn and understand. This concept is especially important in functional programming.
A pure function is a function that satisfies the following two conditions:
- Given the same input, it always returns the same output.
- Causes no side effects outside the function’s scope.
Let’s look at the examples of the pure and impure functions:
One of the ways to understand that the function is impure is to check if it makes sense to call it without using its return value or if it doesn’t return any. These usually indicate that a function causes side effects.
Pure functions should be the basic bricks of your applications. Pure functions are reliable, predictable, and easy to test. If there is a case where you understand that your function does more than one action, then you should find a way on how to split it into several pure functions which can then be combined.