for (let i = 0; i < courses.length; i++) {
courses[i].lastModified = new Date();
}courses.map((course) => {
course.lastModified = new Date();
return course;
})Functional Programming is the process of building software by composing pure functions, avoiding shared state, mutable data, and side-effects. - Eric Elliot
// Immutable Sort example
const initialArray = ['c', 'd', 'a', 'e', 'b'];
const sortedArray = sortFunction(initialArray);
// sortedArray = ['a', 'b', 'c', 'd', 'e']
// initialArray = ['c', 'd', 'a', 'e', 'b']| Functional Programming | vs. | Object-Oriented Programming |
|---|---|---|
| Function is main unit | Object is primary unit | |
| Data is immutable | Data is mutable | |
| Fewer data structures | More data structures | |
| Functions with no side effects | Methods with side effects |
_________ ________
| | | |
| V | V
[Input] -> [FuncA] [FuncB] [FuncB] -> [Output]// Syntax
function1(function2(value))
// Example
const compose = (f, g) => x => f(g(x));
const getAge = (user) => user.age;
const isAllowedAge = (age) => age >= 21;
const user = { name: "Adam", age: 25 };
const isUserAllowedToDrink = compose(isAllowedAge, getAge);
isUserAllowedToDrink(user); // true// Looping approach
const countToTen = (number) => {
for (let i = number; i < 11; i++) {
console.log(i);
}
};
countToTen(1);
const countToTenRecursive = (number) => {
if (number >= 11) return;
console.log(number);
countToTenRecursive(number + 1);
};
countToTenRecursive(1);Array.prototype.filter, Array.prototype.map, and Array.prototype.reduce are all examples of higher-order functions// simple example
const add = (n1, n2) => n1 + n2;
const subtract = (n1, n2) => n1 - n2;
const multiply = (n1, n2) => n1 * n2;
const compute = (mathOperation, initialValue, values) => {
let total = initialValue;
values.forEach((value) => {
total = mathOperation(total, value);
});
return total;
};
console.log(compute(add, 0, [2, 4])); // 6
console.log(compute(subtract, 10, [5, 2])); // 3
console.log(compute(multiply, 1, [2, 4])); // 8f(a, b, c) -> f(a)(b)(c)const add = (a, b, c) => a + b + c;
console.log(add(5, 10, 20));
const addUsingCurrying = (a) => (b) => (c) => a + b + c;
console.log(add(5)(10)(20));
const sendMessage = (greeting) => (name) => (message) =>
`${greeting} ${name}, ${message}`
console.log(sendMessage("Hello")("Andy")("you are learning Currying"));