Pure and Impure functions
Why I am writing about pure functions and impure functions ?
We have talked about react components and I am going to give an example of functions and will talk about why we have to use pure function or impure function .
Let’s look upon this code .
const firstname= ["Raman"]function addLastName(lastName){
firstname.push(lastName)
}
addLastName("Rammurti")
//firstname = ['Raman', 'Rammurti']
addLastName("Raman")//firstname = ['Raman', 'Rammurti', 'Raman']
We have declared a firstname variable and a function addLastName . And As fuction suggest we are going to add the last name in firstname . firstname is external variable , it will be changed after calling the function . Now you have notice at function call , if you don’t have read the whole file .It is obvious , you can’t estimate what will be the output for this . And If you have called mistakenly the function again , it will change the external variable .
Now Imagine if you are working with an ecommerce company also working with new feature like discout code or coupon code .So customer can apply the coupon code in the current price.
let currentP= 1234function addCoupon(couponCode){
if(couponCode){
currentP= currentP*0.96}}
addCoupon("ABC")
currentP
1184.6399999999999
This is not the real case scenario ,customer can not apply discount code again and again . But now customer has changed the global price 😂. And again customer will tap the discount button , customer can set a new price for the users. So funny , but I will assure that you will not write this code for company.
There is multiple side effects of this code . Take a look upon this code.
function addCoupon(){
let price= 2;
price= price*.6;
return price;
}
This function will work as the expected . And the price can’t be changed after multiple time function call , it will be 1.2 every time .
And this is perfect time to discuss about pure functions and Impure functions.
What is an Impure Function?
We have seen the first code. It was having some side effects like , it depend upon external object , it can modify the external object . We can’t estimate about the output without reading the whole documentation or file.
So that type of functions are impure functions . These type of functions have one or more than one side effects .
What is an Pure Function?
Pure function , these type of function don’t have any side effects .
Mutation — Modification can create an error .
Dependent — Dependency can create an error .
Non- Deterministic- Not sure about the output .