JavaScript Higher Order Functions and Callbacks
Understanding Higher Order Functions (HOF)
A Higher Order Function is a function that either takes one or more functions as arguments or returns a function as its result. HOFs are a powerful feature of JavaScript that allows for more abstract and flexible code.
Example 1: Callback Function
function callback(name){
console.log(`Hello ${name}`)
}
function greetings(name, cb){
let greet = "Good Afternoon"
cb(`${name}, ${greet}`)
}
greetings("John", function(name){
console.log(`Hello ${name}`)
});
In this example, greetings
is a function that takes a name and a callback function cb
. It constructs a greeting message and passes it to the callback, which logs the message to the console.
Example 2: Arrow Function as a Callback
const greetings = (name, cb) => {
let greet = "Good Afternoon"
cb(`${name}, ${greet}`)
}
greetings("Death Code", (name) => {
console.log(`Hello ${name}`)
});
This example demonstrates the use of an arrow function as a callback. The syntax is more concise, making the code easier to read while achieving the same functionality as the previous example.
Example 3: Higher Order Function with Return
function multiplier(factor) {
return (num) => {
console.log(num * factor)
return num * factor
}
}
let double = multiplier(2)
let triple = multiplier(3)
let fourMultiplier = multiplier(4)
double(8)
triple(8)
fourMultiplier(8)
The multiplier
function is a higher order function that takes a factor
as an argument and returns another function. This returned function takes a number and multiplies it by the factor. We create three functions: double
, triple
, and fourMultiplier
, each with different multiplication factors.
Conclusion
In this document, we explored Higher Order Functions, callbacks, and arrow functions in JavaScript. HOFs allow for more flexible and reusable code, while callbacks enable asynchronous programming patterns. Understanding these concepts is essential for writing efficient and maintainable JavaScript code. In future lectures, we will also cover array methods like map
, filter
, reduce
, and forEach
that utilize these concepts.
Thank you for learning with us!