Hey Devs! π
Functional programming (FP) in JavaScript helps you write cleaner, more predictable, and easier-to-maintain code.
π Why Functional Programming?
β»οΈ Immutability: Avoid bugs by never changing data directly.
π Pure Functions: Functions without side effects = predictable behavior.
π§ Higher-Order Functions: Pass functions as arguments or return them.
π Declarative Code: Focus on what you want, not how to do it.
π Core Concepts with Examples
1οΈβ£ Pure Functions β¨
-> Same input β same output, no side effects.
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
2οΈβ£ Immutability π‘οΈ
-> Never mutate data directly; create new copies instead.
const person = { name: "Alice", age: 25 };
const updatedPerson = { ...person, age: 26 };
console.log(person.age); // 25
console.log(updatedPerson.age); // 26
3οΈβ£ Higher-Order Functions (HOFs) π
-> Functions that accept or return other functions.
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
4οΈβ£ Closures π
-> Functions that remember the environment where they were created.
function makeCounter() {
let count = 0;
return function() {
count += 1;
return count;
}
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
5οΈβ£ Currying & Partial Application π―
-> Transform functions to accept arguments one at a time.
function multiply(a) {
return function(b) {
return a * b;
}
}
const double = multiply(2);
console.log(double(5)); // 10
6οΈβ£ Recursion π
-> Solve problems by having functions call themselves.
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
π Quick Tip: Using .reduce() to Sum an Array
const nums = [1, 2, 3, 4, 5];
const sum = nums.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // 15
π‘ Why FP Matters for JavaScript Developers
π Reduce Bugs: Minimizes side effects, a common bug source in big apps.
π― Declarative Code: Focus on what to do, not how to do it.
π§© Modular & Testable: Easier to maintain and scale your code.
βοΈ Modern Tools: Powers libraries like React, Redux, Ramda, and Lodash FP.
π¬ Which functional programming techniques do you use in JavaScript? Share your tips or questions below! ππ
Top comments (0)