I saw this impure function on Udacity, but I think it's pure - I am confused. Can some one please explain?
const addAndPrint = (a, b) => {
const sum = a+b;
console.log(`The sum is ${sum}`);
return sum;
};
An impure function is a function that contains one or more side effects. A pure function is a function without any side effects.
Your function is pure if it does not contain any external code. Otherwise, it is impure if it includes one or more side effects.
An impure function is a function that mutates variables/state/data outside of it's lexical scope, thus deeming it “impure” for this reason. There are many ways to write JavaScript, and thinking in terms of impure/pure functions we can write code that is much easier to reason with.
An impure function is kind of the opposite of a pure one - it doesn't predictably produce the same result given the same inputs when called multiple times, and may cause side-effects.
It is not a pure function, because
console.log(`The sum is ${sum}`);
violates point 2:
- Evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices
For the same input it will always give you the same result. You don't have any outer references inside your function, so it depends only on the input
parameters.
Something that can be considered as impure inside your function is that, (not related to the return value) somebody can change the console
's log
function to do another thing.
For example
const addAndPrint = (a, b) => {
const sum = a+b;
console.log(`The sum is ${sum}`);
return sum;
};
console.log(addAndPrint(4,5));
const log = console.log;
console.log = (t) => log('Not the same output');
console.log(addAndPrint(4,5));
And as @Nina answered, it violates to the second point, so based on the pure function's declaration, it is not a pure function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With