Featured
- Get link
- X
- Other Apps
🧠Day 14 — Higher-Order Functions & Callbacks in JavaScript
🧠Day 14 — Higher-Order Functions & Callbacks in JavaScript
Hi Guys
Welcome to Day 14 💡
Today, we enter one of the most powerful areas of JavaScript — **Functional Programming**.
If you’ve ever used methods like map(), filter(), or reduce(), you’ve already used higher-order functions!
Let’s understand how these work and how **callbacks** make your code dynamic and flexible.
🔹 1️⃣ What is a Function?
Functions are reusable blocks of code. But in JavaScript, functions are **first-class citizens**, meaning they can be passed as arguments, returned from other functions, or stored in variables.
🔹 2️⃣ What is a Callback Function?
A callback is a function passed as an argument to another function. It’s called later — hence the name “callback.”
function greet(name, callback) {
console.log("Hello " + name);
callback();
}
function bye() {
console.log("Goodbye!");
}
greet("Rahul", bye);
🔸 3️⃣ Higher-Order Functions
A **Higher-Order Function (HOF)** is any function that takes another function as an argument or returns one.
function operate(a, b, operation) {
return operation(a, b);
}
function add(x, y) { return x + y; }
function multiply(x, y) { return x * y; }
console.log(operate(5, 2, add)); // 7
console.log(operate(5, 2, multiply)); // 10
🔹 4️⃣ Real-Life Use — Array Methods
The most common higher-order functions are map(), filter(), and reduce().
map()
Transforms each element and returns a new array.
let numbers = [1, 2, 3, 4]; let doubled = numbers.map(num => num * 2); console.log(doubled);
filter()
Filters elements based on a condition.
let ages = [10, 18, 21, 30]; let adults = ages.filter(age => age >= 18); console.log(adults);
reduce()
Reduces an array to a single value.
let total = numbers.reduce((sum, num) => sum + num, 0); console.log(total);
💡 5️⃣ Anonymous Functions
Sometimes, callbacks are written without names — called anonymous functions.
setTimeout(function() {
console.log("Executed after 2 seconds");
}, 2000);
🧠6️⃣ Practice Task
- Write a function that accepts a callback to print “Processing...” before executing another function.
- Use
map()to double all numbers in an array. - Use
filter()to extract even numbers. - Use
reduce()to calculate the sum.
🎯 Summary
Higher-Order Functions and Callbacks make JavaScript more flexible, reusable, and asynchronous.
In the next session, you’ll learn how to **control time and delays** using setTimeout() and setInterval().
Popular Posts
💙 Day 27: Bootstrap Mini Project – Responsive Portfolio Page
- Get link
- X
- Other Apps
🎨 Day 2: Headings, Paragraphs & Text Formatting
- Get link
- X
- Other Apps
Comments
Post a Comment