Functional programming is a programming paradigm that focuses on the use of immutable data structures, pure functions, higher-order functions, and recursion to achieve the desired output. In other words, it emphasizes writing code that produces the same results given the same inputs, and avoids modifying state or using mutable data.
In JavaScript, functional programming concepts can be applied in a number of ways. Here is an example:
Suppose you have an array of numbers, and you want to find the sum of all even numbers in the array. One way to write this code using imperative programming is to loop through the array and check each element to see if it is even, and then add it to a running total. Here's how you might write it:
let sum = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
sum += arr[i];
}
}
console.log(sum);
However, using functional programming concepts, you can write this code more concisely and efficiently using a higher-order function:
const sumEvenNumbers = (arr) => {
return arr.reduce((sum, num) => (num % 2 === 0 ? sum + num : sum), 0);
};
console.log(sumEvenNumbers(arr));
This code uses the reduce
method to iterate over the array and accumulate the sum of all even numbers using a higher-order function that takes two arguments: an accumulator (initial value of sum
) and the current element in the array.
By using functional programming concepts, you can write more concise and expressive code that is easier to read, maintain, and scale.