What are pure and impure functions?
Pure functions:
These are functions which are sure to provide exact result when the same arguments are passed. For having a function as pure function if must not have any external variable, data store call, ajax request or any other global variables.
This means that you can be completely sure that every time you call the function with the same arguments, you will always get the same result.
Example:
function square(x){ return x*x }
The above function is pure function as we are always certain what will be result and there will be no different results for same input.
Impure Functions:
When function uses any variables not passed in as arguments, the variables used inside functions may cause side effects. Lets say in case of ajax calls it will fail, In such cases the function is called impure function. When a function depends on variables or functions outside of its lexical scope, you can never be sure that the function will behave the same every time it’s called. Following are impure functions:
function getRandom(number) { a = Math.random() if(a > 10){ return a } else{ return 10 } }
Here the function getRandom is impure as it is not sure what will be the result when we call the function.
So this is the difference between pure and impure functions.
Liked the article please share and subscribe.
2 COMMENTS
And Pure function also it does not change the passed arguments instead it makes the copy of the arguments and then makes the changes .
[…] Try to write pure functions instead of impure functions. Read here about pure and impure functions […]