-
Book Overview & Buying
-
Table Of Contents
Professional JavaScript
By :
Pure functions are functions that don't have side effects and for the same input, arguments will return the same output value(s). A side effect can be anything from mutating the value of an argument passed by reference (which in JavaScript mutates the original) to mutating the value of a local variable, or doing any sort of I/O.
A pure function can be thought of as a mathematical function. It only operates using input and only affects its own output.
Here is a simple pure function, the identity function, which returns whatever is passed to it as a parameter:
const identity = i => i;
Notice how there are no side effects and no mutation of parameters or creation of new variables. This function doesn't even have a body.
Pure functions have the advantage of being simple to reason about. They're also easy to test; there is usually no need to mock any dependencies out since any and all dependencies should be passed as arguments. Pure functions...
Change the font size
Change margin width
Change background colour