Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this function pure or impure? [duplicate]

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;
};
like image 330
CodeNinja101 Avatar asked Sep 05 '17 07:09

CodeNinja101


People also ask

What is pure and impure function?

An impure function is a function that contains one or more side effects. A pure function is a function without any side effects.

How do you know if a function is pure or not?

Your function is pure if it does not contain any external code. Otherwise, it is impure if it includes one or more side effects.

What is an impure function?

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.

What is an impure function in C++?

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.


2 Answers

It is not a pure function, because

console.log(`The sum is ${sum}`);

violates point 2:

  1. 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
like image 177
Nina Scholz Avatar answered Nov 10 '22 01:11

Nina Scholz


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.

like image 33
Suren Srapyan Avatar answered Nov 09 '22 23:11

Suren Srapyan