What's the difference between Pure and Impure functions?
Impure functions: They may change the passed in arguments and their return value doesn't solely depend on the arguments i.e functions that return values that depends on random calls. This they may generate different return value on different function...
usmahm.hashnode.dev1 min read
I think this maybe misses the mark a bit on purity and impurity.
Your first function is indeed impure but not quite for the reasons you say. Let's remove the call to
Math.random()and consider the following:const increment = (num) => { num += 1 return num }Your gut reaction might be to determine this function as impure because there is mutability; the value of
numchanged before it was returned. "This is a side effect" you might say.But let's take a moment to consider what a side effect actually is:
With this knowledge, we can look at our
incrementfunction and determine it has no observable side effects. What happens inside the function has no bearing on the result of our program. Callingincrement(1)will always produce2and from the perspective of the caller, nothing else happens.On the other hand if we bring back the
Math.random()call to give us:const increment = (num) => { num += 1 return num * Math.random() }Now this is impure. That randomness is an observable side effect of running the function. Every time we run
increment(1)we get something different.Let's turn our attention to a property of impure functions you mention:
This is only partially true. If we take our first function and add a global variable:
const x = 1 const increment = (num) => { num += x return num }then by your definition, this function would be impure.
xis known as a free variable, and as long as free variables can't change, then we can say a function that uses them can still be pure providing it has no side effects too.There are some gotchas with those though, particular because of javascript's semantics.
const obj = { x: 10 } const increment = (num) => { num += obj.x return num }We can't reasonably assert that this version of
implementis pure, becauseobj.xcan change.Hope this maybe clears a few bits up!