r/javascript • • Aug 27 '16

Is your JavaScript function actually pure?

http://staltz.com/is-your-javascript-function-actually-pure.html
8 Upvotes

48 comments sorted by

View all comments

1

u/r2d2_21 Aug 27 '16

Math.random

That's cheating.

1

u/g_b Sep 19 '16

It could be any impure function instead of Math.random and the point would still stand.

1

u/r2d2_21 Sep 19 '16

OK, fair enough. Let me correct myself.


Messing with the internal workings of the language

That's cheating.

2

u/g_b Sep 19 '16

You can use any normal function without messing with anything.

function pure(x, callback) {
  return callback(x);
}

if you call a pure function with an impure function as parameter:

var y = 0;
function impure(x) {
  return x + y++; 
}

pure(1, impure);
pure(1, impure);

You get different output even though the arguments are the same.

The pure function will no longer be pure.

2

u/r2d2_21 Sep 19 '16

Yes, that makes sense. It's just that the article went for a convoluted proof.