Table of contents
Welcome back to our JavaScript series! Today, we’ll explore Functional Programming (FP) in JavaScript. FP is a programming paradigm focused on writing pure functions and avoiding side effects. It treats computation as the evaluation of mathematical functions and emphasizes immutability and first-class functions.
What is Functional Programming?
Functional Programming is a programming paradigm that treats computation as the evaluation of functions. It emphasizes the use of pure functions, immutability, and higher-order functions.
Key Concepts of Functional Programming
1. Pure Functions
A pure function is a function that, given the same input, always returns the same output and has no side effects.
Example:
// Pure function
function add(a, b) {
return a + b;
}
// Impure function (has side effects)
let count = 0;
function increment() {
count++;
}
2. Immutability
Immutability means that an object’s state cannot be modified after it is created. Instead of changing the original object, new objects are created with the updated values.
Example:
const arr = [1, 2, 3];
const newArr = [...arr, 4]; // [1, 2, 3, 4]
3. Higher-Order Functions
Higher-order functions are functions that take other functions as arguments or return functions as their result.
Example:
function higherOrder(fn) {
return function(x) {
return fn(x);
};
}
const square = higherOrder(x => x * x);
console.log(square(5)); // 25
Common Functional Programming Techniques in JavaScript
1. Map, Filter, and Reduce
These array methods are commonly used in FP for transforming and processing data.
Map: map
creates a new array by applying a function to each element of the original array.
Example:
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
Filter: filter
creates a new array with all elements that pass the test implemented by the provided function.
Example:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
Reduce: reduce
applies a function against an accumulator and each element in the array to reduce it to a single value.
Example:
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
2. Function Composition
Function composition is the process of combining two or more functions to produce a new function.
Example:
const add = a => b => a + b;
const multiply = a => b => a * b;
const addAndMultiply = x => multiply(2)(add(3)(x));
console.log(addAndMultiply(5)); // (5 + 3) * 2 = 16
3. Currying
Currying is the process of transforming a function that takes multiple arguments into a series of functions that each take a single argument.
Example:
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn(...args);
} else {
return function(...args2) {
return curried(...args.concat(args2));
};
}
};
}
function add(a, b) {
return a + b;
}
const curriedAdd = curry(add);
console.log(curriedAdd(1)(2)); // 3
4. Recursion
Recursion is a technique where a function calls itself in order to solve a problem.
Example:
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
Advantages of Functional Programming
Modularity: Code is broken into small, reusable functions.
Predictability: Pure functions are predictable and easier to test.
Immutability: Reduces the likelihood of bugs caused by changing state.
Concurrency: Easier to handle parallel execution since there are no side effects.
Summary
Today, we explored the fundamentals of Functional Programming in JavaScript. We covered pure functions, immutability, higher-order functions, and common FP techniques like map, filter, reduce, function composition, currying, and recursion. FP helps in writing clean, predictable, and maintainable code. In the coming days, we’ll continue to delve deeper into advanced JavaScript topics. So stay tuned!