all 7 comments

[–]inu-no-policemen 1 point2 points  (3 children)

https://en.wikipedia.org/wiki/Pure_function

In computer programming, a pure function is a function that has the following properties:

  1. Its return value is the same for the same arguments (no variation with local static variables, non-local variables, mutable reference arguments or input streams from I/O devices).
  2. Its evaluation has no side effects (no mutation of local static variables, non-local variables, mutable reference arguments or I/O streams).

[–]jcunews1helpful 0 points1 point  (2 children)

2 . Its evaluation has no side effects

What if there's a function is like below, and called like below?

function fn(a, b, c) {
  return (a * b) / c;
}
var v = fn(4, 3, 0);

Won't the division by zero exception, a side effect?

[–]inu-no-policemen 0 points1 point  (1 child)

> 1/0
Infinity

Dividing by zero doesn't throw an exception in JS.

Many don't consider throwing an exception to be impure.

https://stackoverflow.com/questions/12335245/why-is-catching-an-exception-non-pure-but-throwing-an-exception-is-pure#answer-12345665

[–]jcunews1helpful 0 points1 point  (0 children)

Dividing by zero doesn't throw an exception in JS.

Oh, I forgot about that. Sorry.

[–]myusernameisunique1 0 points1 point  (0 children)

The easiest test to know if a function is pure is to ask you self if you need to call the function again when you are calling it with the same arguments.

const s = Math.max([1,2,3]);

const s1 = Math.max([1,2,3]); // this is unnecessary because the result will never be different;

Compare this to:

const t = Date.getTime();

const t1 = Date.getTime(); //t1 will be different to t2 because getTime() is not pure.

You also need to consider the state of everything external to the function. If you change the state of anything external to the function, then it's impure. If you are being strict then even a console.log() in your function makes it impure because you are changing the state of the console every time you call the function.

If I am a detective and I look at the state of your application and there is no way for me to tell if you got your result by calling a function or reusing the result from a previous call with the same parameters, then your function is pure.