Functional Programming
Functional programming focuses on using functions
that avoid shared states, mutable data, and side effects. It emphasizes pure functions and operations like map
, filter
, and reduce
for clean, concise, and predictable code.
Core Functions of Functional Programming
1.map()
- Transforms each element in an array using a callback function and returns a new array.
- Syntax: array.map(callback) Examples:
Squares and Cubes
const numbers = [1, 2, 3, 4, 5];
function square(element) {
return Math.pow(element, 2);
}
function cube(element) {
return Math.pow(element, 3);
}
const squares = numbers.map(square);
const cubes = numbers.map(cube);
console.log(squares); // [1, 4, 9, 16, 25]
console.log(cubes); // [1, 8, 27, 64, 125]
Formatting Dates
const dates = ["2024-1-10", "2025-2-20", "2026-3-30"];
function formatDate(element) {
const parts = element.split("-");
return `${parts[1]}/${parts[2]}/${parts[0]}`;
}
const formattedDates = dates.map(formatDate);
console.log(formattedDates); // ['1/10/2024', '2/20/2025', '3/30/2026']
2.filter()
- Creates a new array by filtering out elements that don't satisfy a given condition (callback).
- Syntax: array.filter(callback) Examples:
Even and Odd Numbers
const numbers = [1, 2, 3, 4, 5, 6, 7];
function isEven(element) {
return element % 2 === 0;
}
function isOdd(element) {
return element % 2 !== 0;
}
const evenNums = numbers.filter(isEven);
const oddNums = numbers.filter(isOdd);
console.log(evenNums); // [2, 4, 6]
console.log(oddNums); // [1, 3, 5, 7]
Filter Adults (Age >= 18)
const ages = [16, 17, 18, 18, 19, 20, 60];
function isAdult(element) {
return element >= 18;
}
const adults = ages.filter(isAdult);
console.log(adults); // [18, 18, 19, 20, 60]
3.reduce()
- Reduces the array to a single value by applying a callback function iteratively.
- Syntax: array.reduce(callback, initialValue) Examples:
Sum of Prices
const prices = [5, 30, 10, 25, 15, 20];
function sum(previous, next) {
return previous + next;
}
const total = prices.reduce(sum);
console.log(`$${total.toFixed(2)}`); // $105.00
Find Maximum Grade
const grades = [75, 50, 90, 80, 65, 95];
function getMax(accumulator, element) {
return Math.max(accumulator, element);
}
const maximum = grades.reduce(getMax);
console.log(maximum); // 95
Reflection
What I Learned:
- How to transform arrays using map.
- Filtering arrays based on conditions using filter.
- Reducing arrays to a single value (sum, maximum) using reduce.
I'm loving this growth.
Top comments (0)