This content originally appeared on DEV Community and was authored by Nikita Kozlov
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, ...
off the top
If I understand wiki definition of side effects, this means that reading environment doesn't actually count as a side-effect, does it?
Is function which reads current time - function with side effects?
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]
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()
Resources:
wiki/pure_functinos
wiki/side_effect
Other posts:
- JS interview in 2 minutes / Closure
- JS interview in 2 minutes / Currying ?
- JS interview in 2 minutes / Promise
Btw, I will post more fun stuff here and on Twitter. Let's be friends ?
This content originally appeared on DEV Community and was authored by Nikita Kozlov
Nikita Kozlov | Sciencx (2021-05-21T11:40:55+00:00) JS interview in 2 minutes / pure vs impure functions. Retrieved from https://www.scien.cx/2021/05/21/js-interview-in-2-minutes-pure-vs-impure-functions/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.