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;
};
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;
};
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.