🚀 Day 38 of
#100DaysOfCode
Today I dug deeper into callback functions and higher-order functions, two powerful concepts that shape how JavaScript handles logic and flexibility.
🔹 Callback Functions
A callback is simply a function passed as an argument to another function.
They allow code to be executed after another operation has finished.
Example with forEach:
let numbers = [1, 2, 3, 4, 5];
numbers.forEach(num => console.log(num * 2));
// Output: 2, 4, 6, 8, 10
The callback here (num => console.log(num * 2)) is run once for each element.
forEach can pass element, index, and array into the callback.
🔹 Higher-Order Functions
A higher-order function (HOF) either:
✅ Takes one or more functions as arguments
✅ Returns a function
✅ Or both
Example:
function operateOnArray(arr, operation) {
let result = [];
for (let i = 0; i < arr.length; i ) {
result.push(operation(arr[i]));
}
return result;
}
function double(x) { return x * 2; }
console.log(operateOnArray([1,2,3], double));
// [2, 4, 6]
HOFs make code reusable and modular.
Built-in examples: map(), filter(), reduce().
✨ Takeaway:
Callbacks give us fine control over execution, while higher-order functions unlock flexibility by letting us treat functions as data. This combination is the backbone of functional programming in JavaScript.