JS interview in 2 minutes / pure vs impure functions

hexnickk

Nick K

Posted on May 21, 2021

JS interview in 2 minutes / pure vs impure functions

Question:
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

Resources:
wiki/pure_functinos
wiki/side_effect

Other posts:


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

💖 💪 🙅 🚩
hexnickk
Nick K

Posted on May 21, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related