Pure and Impure Functions in JavaScript
Pure Functions
A Pure function is a function that does not modify any external variable. And the Impure function modifies the external variable.
A basic principle of functional programming is that it avoids changing the application state and variables outside its scope. Let see how it works in React.
var s=10;
exampleOfPureFunc=(a,b)=>{
return a+b;
}
exampleOfPureFunc(10,5);
A pure function just takes some input and returns the output accordingly but it never changes any state of the component, it does not affect any external variables as well, like the value of s=10; so a pure function doesn’t any effect on this global variable.
- You can say that pure functions have no side effects.
- Pure functions must not rely on variables outside their scope
- Examples of pure functions are strlen(), pow(), sqrt(), array.length etc
Impure Functions
Impure Functions have side effects it does make changes on external variables like this.
exampleOfImpureFunc = (a, b) => {
s = s + a + b;
return s;
}
exampleOfImpureFunc(10, 5);
// one more example here
// I am just creating a fake Object
const user = {
username: “Azeemaleem”,
password: “pakistan”
}
let isValidate = false
const validator = (user) => {
if (user.username.length > 5 && user.password.length > 5) {
isValidate = true;
}
}
validator(user);
console.log(isValidate); //The value will be true.
You can see that it is causing a side effect(changes) on the external variable. Examples of impure functions are printf(), rand(), time(), etc.
Thanks for visit
Please follow me on LinkedIn