In JavaScript, pure functions and side effects are concepts related to how functions behave and interact with the external world.
Pure Functions:
- A pure function is deterministic; it produces the same output for the same set of inputs.
- It has no observable side effects, meaning it doesn’t modify external state, perform I/O operations, or manipulate the DOM.
- A pure function does not mutate its input parameters or any external variables.
- It exhibits referential transparency, i.e., the function can be replaced with its result without affecting the program’s behavior. This property is essential for reasoning about code and optimizing it.
- Pure functions are favored in functional programming for their simplicity, predictability, and ease of testing.
Example of a Pure Function with Conditions:
// Pure Function
function multiply(a, b) {
return a * b;
}
Example of an Impure Function (not meeting conditions):
// Impure Function (with side effect and mutation)
let total = 0;
function addToTotal(value) {
total += value; // Modifies external state (side effect)
}
// Impure Function (mutating input)
function addOneAndPrint(array) {
array.push(1); // Modifies the input array (mutation)
console.log(array); // Logs to console (side effect)
}
Side Effects:
- Side effects are observable changes in the system caused by a function, such as modifying external state or performing I/O operations.
- Functions with side effects may exhibit unpredictable behavior and are harder to reason about.
- Side effects can include actions like modifying variables outside the function(or writing to storage), logging to the console(or other I/O operations), subscriptions, making async API calls, or manipulating the DOM.
- Pure functions, by definition, avoid side effects and contribute to a more predictable and reliable codebase.
Example of a Function with Side Effect:
let total = 0;
function addToTotal(value) {
total += value; // Modifies external state (side effect)
}
function writeToConsole(message) {
console.log(message); // Logs to console (I/O side effect)
}