A pure function is a function that preserves the integrity of a program by consistently producing the same output for the same input, without altering its overall state. In practical terms, a pure function has no impact outside its own context, thus avoiding any side effects on the program. Rather than directly modifying the original data, a pure function creates and returns new data structures, such as arrays or objects. By using techniques like map(), reduce(), filter(), and other array transformation functions, it is easy to design pure functions.
For example, consider a pure function named squareArray(arr) that squares each element of an array. When applied to an input array, this function will return a new array without altering the original. Here’s an overview of how it works:
“`javascript
function squareArray(arr) {
return arr.map((num) => num * num);
}
console.log(squareArray([1, 2, 3, 4])); // Returns [1, 4, 9, 16]
“`
For comparison, a non-pure version of this function would directly modify the initial array, as illustrated below:
“`javascript
const data = [1, 2, 3, 4];
function squareArray(arr) {
for (let i = 0; i < arr.length; i++) {
arr[i] *= arr[i];
}
return arr;
}
console.log(squareArray(data)); // Returns [1, 4, 9, 16]
console.log(data); // Returns [1, 2, 3, 4]
By adopting functional programming approaches and favoring pure functions, it is possible to guarantee better predictability and more efficient data management within programs.