Is this a pure function?

The dollarToEuro‘s return value depends on an outside variable that is not an argument; therefore, the function is impure.

If the answer is NO, how then can we refactor the function to be pure?

One option is to pass in exchangeRate. This way, every time arguments are (something, somethingElse), the output is guaranteed to be something * somethingElse:

const exchangeRate =  fetchFromDatabase(); // evaluates to say 0.9 for today;

const dollarToEuro = (x, exchangeRate) => {
  return x * exchangeRate;
};

Note that for functional programming, you should avoid let – always use const to avoid reassignment.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)