Pure Functions
What is a pure function? You may have heard your instructor mention this when speaking about functional programming or react/redux apps but what do they mean? We’ll delve into what makes a function pure and why they’re important in this blog.
A pure function is when given the same input will always return the same output with no side effects.
To understand why pure functions are an essential part of functional programming we also need to understand impure functions and some issues with shared state.
First, impure functions are functions that have any kind of randomness executed within. Functions thats outcomes rely on a certain time will be impure because they will only be correct once every 24 hours. Or functions that return a random number like a number generator. Also a dead giveaway that a function in impure is if you have a function that you don’t plan on using its return, should be your first red flag.
Second, the issues with shared state. Now shared state isn’t inherently a bad thing, but when speaking about pure functions it is. It means the outcome could have its integrity compromised but outside forces. In Javascript there are many concurrencies API I/O, event listeners, web workers, and timeouts can introduce indeterminism into your program. Combine that with shared state, and you’ve got a recipe for bugs.
This is why in my opinion it is best to try to stick with pure functions throughout you code as it will help make your code more dynamic. As well as allowing it be easier to be kept up and worked on in the future.