Who else loves to write side-effects-free functions? I think we, as programmers, all do. Today, in this story, I will walk you through the basic principles of functional programming that will make your coding life easier.
Who else loves to write side-effects-free functions?
I think we, as programmers, all do.
Today, in this story, I will walk you through the basic principles of functional programming that will make your coding life easier.
Let’s get into it.
When it comes to pure functions, you need to remember only two things:
Let’s look at the simple example below:
const DISCOUNT = 0.5; const calculatePrice = price => price * DISCOUNT; let actualPrice = calculatePrice(15); // 7.5
Is the function *calculatePrice *pure? No, it’s not.
Why? Because the global variable DISCOUNT is not passed to the function as an argument. If you change the DISCOUNT’s value, the returning result will also change, although the argument price stays the same.
To make it pure function, you have to add one more parameter to the function like this:
const DISCOUNT = 0.5; const calculatePrice = (price, discount) => price * discount; let actualPrice = calculatePrice(15, DISCOUNT); // 7.5