A pure function is a functional programming idea. You do not need to learn any new syntax to start writing them. Writing a pure function is a programming style. A function is classed as pure if it meets these two statements:
This sounds simple enough, but why bother? If you strive to make as many functions as possible pure, you guarantee that your code:
Simple answer, no. It's impossible to write a whole app with pure functions only. With some conscious effort though you will find that when you consciously try to make each function you write pure, you will end up writing more robust code naturally.
For a simple example, say you have a function that has an array as an argument. If you apply one of the out-of-the-box JS functions like splice(), reverse() on it - then your function is impure, as these functions change the underlining array.
When you mutate arguments, your function is called as 'impure'. Impure functions make life harder. Impure functions are harder to unit test so consequentially increase the chance bugs can occur in your code. In the example above, to keep the function pure, you can clone the array that is passed in, performed the mutation and returned the clone. The original array will remain unchanged and the function is pure.
If a function is impure, so it either:
In your code, sometimes doing these types of operations is inevitable. As I mentioned above, it's impossible to have an app with only pure functions. There is a technical term for these conditions, side-effects.
Side effects should be avoided because they make your functions behavior unpredictable. When a function has no side effects, it can run anytime you want with no qualms. Given the same input, it will return the same output.
As that simple example demonstrates, when you code, with a bit of conscious effort you can keep your functions pure with some slight refactoring. On a day-to-day basis, if you keep this principle in mind you'll end up writing more robust code.
Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge