A pure function, also known as a deterministic function, is a function in which the same input always produces the same output or return value, and it has no side effects. What I mean by no side effects, is that the function does not change anything outside of its scope. Pure functions produce consistent results. This makes pure functions easier to read, test, and debug. Pure functions exist in a timeless realm. It doesn’t matter when or where they are called. Nothing outside of the function influences the output.
On the other hand, an impure function, also known as a nondeterministic function, is a function that alters the state, data, or variables outside of its scope, aka side effects. Examples of side effects are console.log, DOM queries, mutating the input, changing the file system, and HTTP calls. Impure functions equal inconsistent results. Impure functions are time-dependent. It matters when and where they are called.
I hope that this helps you to understand the differences between pure and impure functions. When you can, it is better to write pure functions since they make your code:
- Easier to read.
- Easier to test.
- Easier to debug.
You are not going to be able to write pure functions all of the time. I don’t want you to think that impure functions are bad. Impure functions have their uses and there is no way to avoid them (come on, you just gotta console.log things sometimes).