Functional programming is a paradigm that treats computation as the evaluation of mathematical functions and avoids changing state and mutable data. In JavaScript, functions are first-class citizens, meaning they can be assigned to variables, passed as arguments to other functions, and returned from functions. This makes JavaScript well-suited for functional programming.
Consider this simple example of doubling numbers in an array:
This code uses a for
loop to iterate over the array, double each number, and push the result into a new array. This is a common pattern in imperative programming. However, we can achieve the same result more concisely using the map
method, which is a higher-order function in JavaScript:
The map
method applies a function to each element of the array and returns a new array with the results. This is an example of functional programming, where we use functions to transform data without changing the original array.
In this case, the num => num * 2
function is a anonymous function (also known as an arrow function or lambda expression) that doubles each number.
Functional programming encourages writing code in a declarative style, where you describe what you want to achieve rather than how to achieve it. This leads to more concise, readable, and maintainable code. In this chapter, we’ll explore various functional programming concepts and techniques in JavaScript.