1. What is a Function?
A function is a process which takes some input, called arguments, and produces some output called a return value. Functions may serve the following purposes:
- Mapping: Produce some output based on given inputs. A function maps input values to output values.
Math.max(2, 8, 5); // 8
- Procedures: A function may be called to perform a sequence of steps. The sequence is known as a procedure, and programming in this style is known as procedural programming.
- I/O: Some functions exist to communicate with other parts of the system, such as the screen, storage, system logs, or network.
2. What is a Pure Function?
A pure function is a function which:
- Given the same input, will always return the same output.
- Non-pure example:
Math.random(); // => 0.4011148700956255
Math.random(); // => 0.8533405303023756
- Pure example:
highpass(5, 5); // => true
highpass(5, 5); // => true
- Non-pure example:
- Produces no side effects, which means that it can’t alter any external state.
- Side effects example:
- Saving value to disk or logging to console
- Side effects example:
- Referential Transparency
- Replace a function call with its resulting value without changing the meaning of the program.