IMPORTANT NOTES TO THE ZEALOTS: Listen to me you functional programming zealot. Writting opaque functions is ok! Chill the F out. This programming style is just another useful skill that elegantly solves certain types of problems. This is NOT the Thor hammer that will crush all your nails you geek. So relaaaax maaaann.
Those two concepts are linked together. A pure function is a function that returns the same output each time the same input is providedm and it must do so with side effects. This means that evaluation of a pure function for a specificic set of inputs can be replaced with its output. The last sentence can be rewritten as follow: A pure function is referentially transparent. The opposite is referential opacity. Let see this with an example:
let counter = 0
const pureIncrementFn = i => i+1
const opaqueIncrementFn = i => {
counter++
return i+counter
}
console.log(pureIncrementFn(1)) // 2
console.log(pureIncrementFn(1)) // 2
console.log(opaqueIncrementFn(1)) // 2
console.log(opaqueIncrementFn(1)) // 3
console.log(opaqueIncrementFn(1)) // 4
The above example shows that opaqueIncrementFn
is undeterministic because each time it is evaluated, it mutates the counter
variable. It is not possible to know for sure what the output will be, there, the following two statements are not equivalent:
opaqueIncrementFn(1) == 2
// and
2 == 2
It is not possible to replace opaqueIncrementFn(1)
with its value. That's why opaqueIncrementFn
is not referentially transparent. Whereas pureIncrementFn
is:
pureIncrementFn(1) == 2
// is equivalent to
2 == 2