DEV Community

loading...
Cover image for Guide to Callbacks & Higher-Order Functions in JavaScript.

Guide to Callbacks & Higher-Order Functions in JavaScript.

Blessing Hirwa
Fullstack web developer πŸ’» | ReactJS enthusiast βš› | Music 🎡 | Blogger | UI Designer | I love and trust Javascript
・Updated on ・3 min read

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
Enter fullscreen mode Exit fullscreen mode
What about a 9 squared function?

nineSquared

function nineSquared() {
 return 9*9;
}
nineSquared() // 81
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);

Enter fullscreen mode Exit fullscreen mode

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 it DRY.

  • 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 of promises, 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!

Discussion (7)

Collapse
didiermunezer38 profile image
Didien Munezero

Woow! this is nice.

Collapse
xvbnm48 profile image
M Fariz Wisnu prananda

thanks for sharing!

Collapse
blessingartcreator profile image
Blessing Hirwa Author

My pleasure.

Collapse
twizeyimanaeli4 profile image
Twizeyimana Elissa

keep it up!

Collapse
oreste profile image
Oreste Abizera

I think you made a mistake in the second example. nineSquared() is returning 100?

Collapse
blessingartcreator profile image
Blessing Hirwa Author

Thank you for pointing it out. I made a typo but the problem is fixed now.

Collapse
oreste profile image
Oreste Abizera

okay