Referential Transparency
A term that is closely associated with pure functions is referential transparency
. Just like how we had previously said a pure function returns the same output for the same input (no matter how many times we invoke it)-- referential transparency means that we can replace a function invocation without changing its meaning. If that was confusing, take a look at the following example.
In it, we can see that 5 + 1 * 2
will give us the output of 12
through two function calls. According to referential transparency, if we put the absolute values that the function returns, it should give us the same output. In our case, this will be 6 * 2
, which is 12
.
xxxxxxxxxx
11
function addOne(a) {
return a + 1;
}
function multiplyTwo(a) {
return a * 2;
}
let x = 5;
console.log("(5 + 1) * 2 is: " + multiplyTwo(addOne(x)));
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment