What is pure?
A pure function is a piece of code that always gives the same output for the same input and never changes anything outside of itself. It doesn’t read or write files, modify global variables, or depend on hidden state - it only works with the values you give it and returns a result.
Let's break it down
- Input → The data you pass into the function (e.g., numbers, strings).
- Output → The value the function returns.
- No side effects → The function doesn’t alter external data, print to the screen, or change a database.
- Deterministic → Call it many times with the same input and you’ll always get the same output.
Why does it matter?
Pure functions are easy to understand, test, and debug because they behave predictably. They also make programs safer to run in parallel (multiple threads) and help tools like compilers and optimizers improve performance automatically.
Where is it used?
- Functional programming languages (Haskell, Elm, Clojure).
- Modern JavaScript/TypeScript codebases that use React, Redux, or other state‑management libraries.
- Data‑processing pipelines, map‑reduce jobs, and any place where you need reliable, repeatable transformations.
Good things about it
- Predictable results → fewer bugs.
- Simple unit testing → just feed inputs and check outputs.
- Easier to reason about code flow.
- Enables memoization (caching results) and parallel execution without race conditions.
Not-so-good things
- Sometimes you need to interact with the outside world (e.g., reading a file), which pure functions can’t do directly.
- Over‑emphasis on purity can lead to overly complex code structures for simple tasks.
- May require extra wrappers or abstractions to handle side effects, adding a learning curve for beginners.