DEV Community

Cover image for JS interview in 2 minutes / pure vs impure functions
Nikita Kozlov
Nikita Kozlov

Posted on • Updated on

JS interview in 2 minutes / pure vs impure functions

Explain the difference between pure and impure functions. What are the side effects?

Quick answer:
A pure function is a function that returns the same result for the same arguments, also this function doesn't have any side effects.

The side-effect is then function modify any data outside of its current scope.

Longer answer:
We can start with side effects, basically, this means that if you have some environment and you run a function with a side effect, something will be changed by this function in this environment.

Possible examples are - writing to file, displaying something to the user, making HTTP requests, modifying global variables, emitting events, ...

As for repeatable results, it is simpler to just give an example.

let add = (a, b) => a + b;
let mult = (a, b) => a * b;
let getProp = (name) => (obj) => obj[name]
Enter fullscreen mode Exit fullscreen mode

All these functions are repeatable because they are providing the same result over the same arguments.

Btw there are no side effects -> they are pure ✨

Real-life applications:
Pure functions significantly simplify testing and debugging, also helps to reuse code easier.

If you don't depend on the environment it will be ridiculously easy to write tests.

Same for reusability, everyone should prefer just using something over setting the environment -> using something -> cleaning the environment.

Can you spot the issue here? 🔎

let headers = [
  ... // some regular headers

function getAuthData() {
  // ...
  headers.push({ Authorization: token })
  return http.get('/data', headers)

function externalService() {
  return http.get('http://other.service/api', headers)

let data1 = getAuthData()
let data2 = externalService()
Enter fullscreen mode Exit fullscreen mode


Other posts:

Btw, I will post more fun stuff here and on Twitter. Let's be friends 👋

Top comments (0)