Functional Programming
Functional programming is a paradigm that treats computation as the evaluation of mathematical functions. It avoids changing state and mutable data. In the chapter on Procedural Programming, we learned that JavaScript functions are first-class values. They can be assigned to variables, passed as arguments, and returned from functions. That is what makes JavaScript a good fit for functional programming, and in this chapter we will look at patterns that build on it.
Here is a simple example. We want to double every number in an array:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = [];
for (let i = 0; i < numbers.length; i++) {
doubledNumbers.push(numbers[i] * 2);
}
console.log(doubledNumbers); // [2, 4, 6, 8, 10]
This code uses a for loop to go over the array, double each number, and push the result into a new array. That is a common pattern in imperative programming. We can get the same result with less code using the map method, which is a higher-order function:
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map((num) => num * 2);
console.log(doubledNumbers); // [2, 4, 6, 8, 10]
The map method applies a function to each element of the array and returns a new array with the results. This is functional programming: we pass a function as an argument to transform data without changing the original array.
Functional programming encourages a declarative style, where you describe what you want rather than how to get it. Code written that way is usually shorter, easier to read, and easier to maintain.
Learning Outcomes
- Explain functional programming as a paradigm and describe how first-class and higher-order functions support it in JavaScript
- Use inner functions and closures to encapsulate helper logic and maintain private state
- Apply currying and function composition to build modular, reusable functions
- Distinguish pure from impure functions and describe the role of immutability in functional code