Module 23 : javascript Higher-Order Functions
๐ง 1. What is a Higher-Order Function?
A Higher-Order Function is a function that takes another function as an argument or returns a function as its result (or both).
javascript
code
function higherOrder(fn) { return function(x) { return fn(x) + 10; }; }
Here:
higherOrder takes a function fn as an argument and returns another function.
That’s the definition of a Higher-Order Function.
⚙️ 2. Built-In Higher-Order Functions
JavaScript provides several built-in HOFs for arrays:
a. .forEach() – Looping
javascript
code
let numbers = [1, 2, 3]; numbers.forEach(num => console.log(num * 2)); // Output: 2, 4, 6
Explanation: .forEach() takes a function and applies it to every element.
b. .map() – Transforming Data
javascript
code
let squared = numbers.map(num => num * num); console.log(squared); // Output: [1, 4, 9]
Explanation: .map() returns a new array by applying a function to every element.
c. .filter() – Filtering Data
javascript
code
let even = numbers.filter(num => num % 2 === 0); console.log(even); // Output: [2]
Explanation: .filter() returns elements that satisfy the given condition.
d. .reduce() – Accumulating Data
javascript
code
let sum = numbers.reduce((acc, curr) => acc + curr, 0); console.log(sum); // Output: 6
Explanation: .reduce() returns a single value by accumulating results from left to right.
๐️ 3. Creating Custom Higher-Order Functions
Here’s how you can create your own HOF:
javascript
code
function repeat(n, action) { for (let i = 0; i < n; i++) { action(i); } } repeat(3, console.log); // Output: 0, 1, 2
Explanation:
repeat is a HOF because it takes action, a function, as a parameter.
4. HOF for Event Handling
๐ป Objective:
Build a HOF that logs messages differently based on user role.
๐ง Code:
javascript
code
function createLogger(role) { return function(message) { console.log(`[${role.toUpperCase()}] ${message}`); } } let adminLogger = createLogger('admin'); let userLogger = createLogger('user'); adminLogger('Deleted a post'); // [ADMIN] Deleted a post userLogger('Liked a post'); // [USER] Liked a post
๐ Analysis:
createLogger is a HOF — it returns another function based on its input.
This can be used to customize behavior for different user roles.
✏️ 5. Exercises
Exercise 1: Custom Map Function
Write your own version of .map().
javascript
code
function customMap(arr, transform) { let result = []; for (let i = 0; i < arr.length; i++) { result.push(transform(arr[i])); } return result; } console.log(customMap([1, 2, 3], x => x * 2)); // Output: [2, 4, 6]
Exercise 2: Filter Names
javascript
code
let names = ["Alice", "Bob", "Charlie", "Anna"]; let filtered = names.filter(name => name.startsWith("A")); console.log(filtered); // Output: ["Alice", "Anna"]
๐ง 6. Conceptual Research
๐น Why Use Higher-Order Functions?
Abstraction: You can abstract logic away into functions.
Modularity: Functions become reusable and composable.
Immutability: Functions like .map() and .filter() do not change the original array.
Readability: Shorter, declarative code.
๐น Use Cases
ReactJS JSX rendering — .map() used to render lists dynamically.
Node.js API routing — Middleware functions are passed as parameters.
Data transformation pipelines — Chaining .map(), .filter(), and .reduce() for processing.
7. Assignment: Creating a Data Pipeline
๐ฏ Goal:
Process a list of students and get average marks of those who passed.
๐งพ Given:
javascript
code
let students = [ { name: "Alice", score: 75 }, { name: "Bob", score: 45 }, { name: "Charlie", score: 85 }, { name: "David", score: 60 } ];
๐งฑ Steps:
Filter those who scored ≥ 60.
Map to extract scores.
Reduce to get the average.
๐ง๐ป Code:
javascript
code
let passed = students .filter(student => student.score >= 60) .map(student => student.score); let avg = passed.reduce((a, b) => a + b, 0) / passed.length; console.log("Average of passed students:", avg);
Output:
shell code
Average of passed students: 73.333...
๐ 8. Summary
Feature
Description
What is HOF
Function that takes or returns another function
Built-in Examples
.map(), .filter(), .reduce(), .forEach()
Custom HOF Example
repeat, createLogger
Benefits
Code reuse, clarity, immutability
Focus
Event customization, data pipelines
Research Direction
Data-driven UI, middleware, functional patterns
๐ 9. Additional Research Topics
Functional Programming in JavaScript
Pure Functions vs. HOFs
Comparison with Object-Oriented Methods
Performance Analysis of HOFs
Using Lodash’s HOFs for Advanced Pipelines
๐ 10. References
Eloquent JavaScript by Marijn Haverbeke
Mozilla MDN Web Docs: https://developer.mozilla.org
Kyle Simpson, You Don’t Know JS
Functional-Light JavaScript by Kyle Simpson (GitHub open source book)
No comments:
Post a Comment