In functional programming paradigm, you achieve the program objective using pure, deterministic functions.
Pure functions
- Output is solely a “function” of their input. Given a specific input, it will always return the same output.
- Does not cause any side effects. Eg. It does not modify global variables.
In short, pure functions acts ( reading + writing ) only on stuff that is local to it.
let currentCount = 0;
// Pure function
function incrementCountPure(currentCount, increment) {
return currentCount + increment;
}
// Impure function
function incrementCountImpure(increment) {
return currentCount + increment;
}
Here, the output of the impure function depends on the global currentCount
variable. Manipulating currentCount
elsewhere can have unexpected effects on the output of incrementCountImpure
. As a result, the system interactions are complex and error prone.
The dependence on external state ( currentCount
in this case ) makes debugging more difficult since an effect could have multiple, possibly undocumented sources. Unit testing is also more deifficult and not as effective since it is impossible to isolate the function.