- Published on
Pure Functions in JavaScript
- Authors
- Name
- Christoph Diehl
- @posidron
A pure function is a function that satisfies these two conditions:
- Given the same input, the function returns the same output.
- The function does not cause side effects outside of the function's scope (i.e. mutate data outside the function or data supplied to the function).
Pure functions can mutate local data within the function as long as it satisfies the two conditions above.
Pure
const a = (x, y) => x + y
const b = (arr, value) => arr.concat(value)
const c = (arr) => [...arr].sort((a, b) => a - b)
Impure
const a = (x, y) => x + y + Math.random()
const b = (arr, value) => (arr.push(value), arr)
const c = (arr) => arr.sort((a, b) => a - b)