What is a pure function exactly?
The simplest definition for a pure function is it gives the same output for the same inputs.
If you take a look at the example code above, you can notice that the pure function is not performing any side effects.
The function just runs based on its arguments, not by external or global variables etc. This is the concept of pure function.
Effectively, a pure function’s return value is based only on its inputs and has no other dependencies or effects on the overall program.
Consider this function, it looks pure because it is not performing any side effects. But this function does not return the same value when we run the function! So it is not pure.
Why pure functions?
Pure functions are much easier to read and understand what exactly they are doing.
All the dependencies and inputs are specified in the parameters so we exactly know what the function is doing since it’s not mutating anything in global scope.
Since a function doesn’t do have any side effects, it is easier to test by passing same inputs and expecting a certain output.
That's all, folks!
If you really liked it and want to get more content like this, you can follow me on Hashnode and on Twitter @syedbasim and I will keep posting stuff like this on:
- 🎨 HTML & CSS
- ⚛ React & Nextjs
- 🟦 TypeScript
- 🏃♂️ My journey & Achievements