By definition, a Pure Function is pure if:
- Given the same input, will always return the same output.
- Produces no side effects.
- Relies on no external state.
So this is a pure function:
function foo(x) { return x * 2; } foo(1) // 2 foo(2) // 4 foo(3) // 6 And this would be a pure function as well (in JavaScript context)
Math.floor(x); Math.floor(1.1); // 1 Math.floor(1.2); // 1 Math.floor(2.2); // 2 The question: if we combine these 2 pure function, would it still be considered as a pure function?
// Nested with Math library function bar(x) { return Math.floor(x); } // Nested even deeper function foobar(x) { return foo(Math.floor(x)); } Obviously, it still always return the same output given the same input without side effects, but does calling a function from other context (scope) break the law for "Relies on no external state"?
foodoesn't rely on any external state and doesn't change its behaviour based on any external statefoobarwill still be a pure function.Math.floorwill become a utility function. Now if I change this utility function, all subscribers will be effected. Do utility function is pure but subscribers are not as they depend on utility.