Callbacks and Higher Order functions are some of the most misunderstood concepts in JavaScript. During this post, we will become familiar with them to write pro-level code as JavaScript engineers.
Before continuing, let's ask ourselves a question.
Why do we even have functions
Letβs see whyβ¦
Create a function 10 squared
- Takes no input
- Returns 10*10
tenSquared
function tenSquared() {
return 10*10;
}
tenSquared() // 100
What about a 9 squared function?
nineSquared
function nineSquared() {
return 9*9;
}
nineSquared() // 81
And an 8 squared function? 125 squared?
What principle are we breaking? DRY (Donβt Repeat Yourself )
π We can generalize the function to make it reusable.
function squareNum(num){
return num*num;
}
squareNum(10); // 100
squareNum(9); // 81
squareNum(8); // 64
Generalizing functions
Parameters (placeholders)
mean we donβt need to decide what data to run our functionality on until we run the function. Then provide an actual value (argument)
when we run the function. Higher-order functions
follow this same principle, we may not want to decide exactly what some of our functionality is until we run our function.
Now suppose we have a function copyArrayAndMultiplyBy2
.
function copyArrayAndMultiplyBy2(array) {
const output = [];
for (let i = 0; i < array.length; i++) {
output.push(array[i] * 2);
}
return output;
}
const myArray = [1,2,3];
const result = copyArrayAndMultiplyBy2(myArray)
What if want to copy the array and divide it by 2?
function copyArrayAndDivideBy2(array) {
const output = [];
for (let i = 0; i < array.length; i++) {
output.push(array[i] / 2);
}
return output;
}
const myArray = [1,2,3];
const result = copyArrayAndDivideBy2(myArray)
Or add 3?
function copyArrayAndAdd3(array) {
const output = [];
for (let i = 0; i < array.length; i++) {
output.push(array[i] + 3);
}
return output;
}
const myArray = [1,2,3];
const result = copyArrayAndAdd3(myArray);
What principle are we breaking? DRY (Donβt Repeat Yourself )
π We could generalize our function, so we pass in our specific instruction only when we run copyArrayAndManipulate
!
function copyArrayAndManipulate(array, instructions) {
const output = [];
for (let i = 0; i < array.length; i++) {
output.push(instructions(array[i]));
}
return output;
}
function multiplyBy2(input) { return input * 2; }
const result = copyArrayAndManipulate([1, 2, 3], multiplyBy2);
How was this possible?
Functions in javascript = first-class objects
. In addition to this, let's highlight some of the other features of functions:
- They can co-exist with and can be treated like any other javascript object
- Assigned to variables and properties of other objects
- Passed as arguments into functions
- Returned as values from functions
Consider this piece of code
function copyArrayAndManipulate(array, instructions) {
const output = [];
for (let i = 0; i < array.length; i++) {
output.push(instructions(array[i]));
}
return output;
}
function multiplyBy2(input) {return input * 2;}
const result = copyArrayAndManipulate([1, 2, 3], multiplyBy2);
Which is our Higher Order Function β?
The outer function that takes in a function is our higher-order.
Which is our Callback Function
The function we insert is our callback function.
Higher-order functions
Takes in a function or passes out a function. Just a term to describe these functions - any function that does it we call that -
but there's nothing different about them inherently.
Why do we need to master these two concepts
Callbacks and Higher-Order Functions simplify our code
and keep itDRY
.Declarative readable code: Map, filter, reduce - the most readable way to write code to work with data.
Codesmith & pro interview prep: One of the most popular topics to test in an interview both for Codesmith and other mid/senior-level job interviews.
Asynchronous JavaScript: Callbacks are a core aspect of
async JavaScript
, and are under the hood ofpromises
,async/await
.
Conclusion
What's more, there we have it. If you made it here thank you for reading! I hope this post will help you get started with writing pro-level JavaScript codes.
πLet's be friends! Follow me on Twitter and instagram for more related content. Don't forget to follow me also here on Dev as well to get updated for new content.
Cheers!
Top comments (9)
I think you made a mistake in the second example. nineSquared() is returning 100?
Thank you for pointing it out. I made a typo but the problem is fixed now.
okay
thanks for sharing!
My pleasure.
Woow! this is nice.
keep it up!
Great work Blessing
My pleasure.