A function is referentially transparent if you can replace a call to it with the result of that call without changing its behavior. Its result depends only on its input.
Pure functions are referentially transparent. An addition function, for example:
let sum = add(5, 6);
The function call’s result can be replaced with its result:
let sum = 11;
Nothing changes in the execution here except the removal of a call to add
.
Here’s an example of a function that isn’t referentially transparent:
let today = getCurrentDate();
I’ll replace getCurrentDate
with its result:
let today = '02/17/2016'; // or something
But if I call getCurrentDate
again tomorrow, I won’t get the same result. I can’t replace the call with the result without changing behavior. So getCurrentDate
is not referentially transparent.