-
Easier to reason about
- a pure function tells everything you need to know about the function. No hidden I/O, no external variables modified, no instance or even global variables to hunt down.
-
Easier to test
- since the same input(s) always return the same output(s), they're easy to test. Provide the input and expected output. Simple! No need for setup, teardown, or mocking.
expect(last([3, 9, 5])).toBe(5) // that's it!
-
Easier to debug
- Debugging is like detective work, and there are less suspects to investigate, since you don't have to worry about mutations, side-effects, and variables outside the pure function.
-
Easier to combine
- Pure functions can act like LEGO blocks, when used with function composition or piping.
-
Easier to parallelize
- Since pure functions don't modify any of its parameters or any outside variables, you can be sure they're thread-safe. The OS can run these functions using any number of cores and in any order.
-
Easier to cache
- Some functions are expensive to calculate, e.g. the permutations of
abcde
. The results of a pure function can be cached, and callingpermutation('abcde')
the second time will be faster, since the result will be retrieved from the 🐇cache rather than 🐢recomputed.
- Some functions are expensive to calculate, e.g. the permutations of
-
and many other benefits
- Referential transparency, laziness, idempotency,... It even makes it easy for bundlers to tree-shake frontend code that's composed of pure functions.
Created
April 26, 2022 03:04
-
-
Save myknbani/d5d66142fc6127a4e941d3e0ea024e70 to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment