DEV Community

Discussion on: Functional Programming Principles in Javascript

Collapse
 
maple3142 profile image
maple • Edited

I thought caculateArea is a pure function.Am I understand wrongly?

function calculateArea(radius) {
  return radius * radius * PI;
}

It will return the same value if you call it with same variable, because PI is a constant.
If you use replace PI with 3.14159 or Math.PI, it should still be a pure function.

Collapse
 
teekay profile image
TK

Yes, Maple, maybe my example was a bit confusing. My attempt was to show that the "constant" PI (an external variable) could change (in my example, I changed it to 42).

If the PI value changes, our calculateArea function will change the output for the same input (radius). The whole idea is to show that the function to be pure, it needs to not change the output, for the same input.

I will try give another example with a variable instead of a constant.

let tax = 20;

const totalPriceWithTax = (productPrice) => (productPrice * (tax / 100)) + productPrice;

For the input 100, we will have 120 as a result. But if our tax changes, our output will change, for the same input (100).

totalPriceWithTax(100); // 120
totalPriceWithTax(100); // 120
tax = 100
totalPriceWithTax(100); // 200

To make our function pure, we can pass the tax variable to the function as a parameter

const totalPriceWithTax = (productPrice, tax) => (productPrice * (tax / 100)) + productPrice;

For the inputs 100 and 20, it will always be 120

totalPriceWithTax(100, 20); // 120
totalPriceWithTax(100, 20); // 120
// ...

For the inputs 100 and 100, it will always be 200

totalPriceWithTax(100, 100); // 200
totalPriceWithTax(100, 100); // 200
// ...

With this example it is a bit less confusing I think.

Thanks for the feedback!

Some comments have been hidden by the post's author - find out more