Javascript tips — Pure functions

Leonardo Bruno Lima
2 min readMar 31, 2018

--

Photo by Jeremy Bishop on Unsplash

The definition of a pure function has basically two statements:

  • The function always returns the same result if the same arguments are passed in. It other words, given the same input, it will always return the same output
  • The function does not produce any semantically observable side effects such as network requests, mutable objects or output to I/O devices, etc.
const mutiply = (x, y) => x * y // Is a pure function

multiply is a pure function because it’s output is dependent on the arguments it receives. Given the same values, it will produce the same output.

Let’s see another example:

const fetchUser = API.getUser(10);

Is fetchUser a pure function? Does it return the same value (user with id 10), right? The answer is no. This function sometimes will work as we expect , but sometimes the server will not respond and we will get a 500 error. The API may change so that this call is no longer valid. So, this function is non-deterministic, that’s why we can say that it is an impure function.

Why should I care about pure functions?

Testability: Because pure functions are deterministic, writing unit tests for them is very simple. They also makes refactoring code much easier. You can change a pure function and not have to worry about side effects messing up the entire application.

Readability: Because side effects, our code become harder to read. A non pure function is not deterministic, so it may return different values for a given input and we end up writing code that needs to deal with all different possibilities.

Modularity: Because they only depend on the input you give them, you can reuse pure functions between different parts of your codebase.

Happy code! Thanks!

--

--