As we know a pure function doesn't depend on and doesn't modify the states of variables out of its scope. I have a clarity on these that if a function is dependent on some arguments it becomes non pure function but why is Date.now()
or Math.random()
called non pure function. Can someone explain me the basics behind it?
Asked
Active
Viewed 1,066 times
2

Steffen Moritz
- 7,277
- 11
- 36
- 55

Tanveer
- 31
- 8
-
Where did you get these definitions from, and who told you / where do you read that Date.now() & Math.random() are not so called "pure" functions? – ControlAltDel Jun 26 '19 at 18:22
-
@ControlAltDel https://en.wikipedia.org/wiki/Pure_function `Date.now()` and `Math.random()` are definitionally not pure. – lux Jun 26 '19 at 18:38
-
Related: https://stackoverflow.com/questions/37244023 . – atravers Jan 13 '22 at 01:38
2 Answers
5
Pure functions:
- Do not depend on or modify external state
- Return the same result every time for the same input
Both functions you mention violate #2 - they return different value everytime you call them. In reality they also violate #1 since they are accessing and/or modifying global state to do their work.

Brandon
- 38,310
- 8
- 82
- 87
1
Your definition is incomplete, let's see e.g. https://en.wikipedia.org/wiki/Pure_function
a function that has the following properties:
- Its return value is the same for the same arguments
- Its evaluation has no side effects
Neither Date.now()
nor Math.random()
meet the 1st point of the definition, so they are not pure functions.