A Beginner's Guide to Higher-Order Function (HOF) in Javascript.

A Beginner's Guide to Higher-Order Function (HOF) in Javascript.

ยท

6 min read

Introduction

Welcome to the exciting world of JavaScript, where coding possibilities unfold at every turn. Today, we're unveiling a concept that might sound complex but holds incredible power for beginners. This concept is called "Higher-Order Function". But before we dive into Higher-order Functions (HOF), we need to understand what a Function is and how to use it.

What is a Function?

A Function is a readable, reusable, maintainable piece of code that performs a specific task or set of tasks. It allows you to organize your code by breaking it into smaller, manageable pieces. For example, if we want to calculate the area of a rectangle without using a function the code would look like this;

// Without using a function

const length = 5;

const width = 10;

const area = length * width;

console.log(`The area of the rectangle is:  ${area}`);
//The area of the rectangle is 50

Now let us write the same piece of code using a function;

// Using a function
function calculateRectangleArea(length, width) {
  return length * width;
}

const length = 5;
const width = 10;
const area = calculateRectangleArea(length, width);
console.log(`The area of the rectangle is: ${area} `);
// The area of the rectangle is 50

What if we want to calculate the area of two different Rectangles;

Calculating the Area of two different rectangles without using a function.

// Without using a function
//calculating the Area of two different Rectangles.
const lengthOfRect1 = 5;

const widthOfRect1 = 10;

const lengthOfRect2 = 8;

const widthOfRect2 = 12;

const areaOfRect1 = lengthOfRect1 * widthOfRect1;

const areaOfRect2 = lengthOfRect2 * widthOfRect2;

console.log(`The area of the first rectangle is:  ${areaOfRect1}`);
//The area of the first rectangle is: 50

console.log(`The area of the second rectangle is:  ${areaOfRect2}`);
//The area of the first rectangle is: 96

Let us write this same piece of code using a function;

//calculating the Area of two different Rectangles.

function calculateRectangleArea(length, width) {
  return length * width;
}

const areaOfRect1 = calculateRectangleArea(5, 10);
const areaOfRect2 = calculateRectangleArea(8, 12);

console.log(`The Area of the first rectangle: ${areaOfRect1}`);
//The area of the first rectangle is: 50

console.log(`The Area of the second rectangle: ${areaOfRect2}`);
//The area of the first rectangle is: 96

Notice how there is a lot of repetition when calculating the Area of two different rectangles without a function. Assuming we were to calculate the Area for twenty or a hundred different Rectangles, there would be a lot of repetition and the code base would be cumbersome, and hard to read and maintain. However, when using a function to encapsulate the logic for calculating the Area of a rectangle, the code becomes more concise, removing redundancy and promoting reusability. This not only streamlines the codebase but also enhances maintainability, as any updates or modifications to the Area calculation can be made in a single location within the function, ensuring consistent and efficient changes across the entire application.

What is a Higher-Order Function(HOF)?

A Higher-order function is a function that takes one or more functions as arguments or returns a function as its result. In JavaScript, functions can be assigned to variables in the same way that strings or arrays can. They can be passed into other functions as parameters or returned from them as well.

How do we use Higher-order Functions?

Let's dive into some examples showing the use cases of Higher-order functions as:

  • a function that takes one or more functions as arguments

  • a function that returns a function as its result.

A Function that takes one or more functions as arguments

In this example, we will build a simple calculator that takes in two numbers and performs the basic arithmetic operation which includes addition, subtraction, multiplication, and division. First, we'll define a higher-order function called operate that takes two numbers and a function as arguments. The function argument will operate on the two numbers.

// A simple calculator
function operate(a, b, operation) {
  return operation(a, b);
}

// Example operation functions
function add(x, y) {
  return x + y;
}

function subtract(x, y) {
  return x - y;
}

function multiply(x, y) {
  return x * y;
}

function divide(x, y) {
  return x / y;
}

// Example usage of the higher-order function
const result1 = operate(5, 3, add);
console.log("Addition result:", result1); 
// Output: Addition result: 8

const result2 = operate(8, 4, subtract);
console.log("Subtraction result:", result2); 
// Output: Subtraction result: 4

const result3 = operate(2, 6, multiply);
console.log("Multiplication result:", result3); 
// Output: Multiplication result: 12

const result4 = operate(10, 2, divide);
console.log("Division result:", result4); 
// Output: Division result: 5

The operate function is a higher-order function that takes two numbers (a and b) and a function (operation) as arguments.

The add, subtract, multiply, and divide functions are operation functions that perform addition, subtraction, multiplication, and division respectively.

A Function that returns a function as its result.

From our simple calculator example, notice that in the operate function we are returning a function called operation as result. This shows that the operate function is a higher-order function that returns a function as a result.

Let's take another example.

// Higher-order function
function createGreeter(greeting) {
  // Returned function
  return function (name) {
    return `${greeting}, ${name}!`;
  };
}

// Example usage
const greetWithHello = createGreeter("Hello");
const greetWithHi = createGreeter("Hi");

// Applying the returned functions
const message1 = greetWithHello("Alice"); // "Hello, Alice!"
const message2 = greetWithHi("Bob"); // "Hi, Bob!"

console.log("Message 1:", message1); // Output: Message 1: Hello, Alice!
console.log("Message 2:", message2); // Output: Message 2: Hi, Bob!

The createGreater function is a higher-order function because it returns a function.

greetWithHello and greetWithHi are functions returned by createGreeter with different greeting messages.

When we call greetWithHello("Alice"), it creates the message "Hello, Alice!", and when we call greetWithHi("Bob"), it creates the message "Hi, Bob!".

Advantages of Higher-order Functions

  • Abstraction: Higher-order functions allow you to abstract away complex logic into reusable, modular components. This enhances the readability and maintainability of your code.

  • Flexibility: Higher-order functions make your code more flexible and adaptable. You can easily modify behavior by changing the functions passed as arguments.

  • Code Reusability: By passing functions as arguments or returning functions, you can reuse code in different contexts. This promotes a DRY (Don't Repeat Yourself) coding practice.

  • Functional Programming Paradigm: Higher-order functions are fundamental to functional programming. Embracing this paradigm can lead to code that is easier to reason about, test, and debug.

In summary, a higher-order function is a function that can take other functions as arguments or return functions as results. It enables the composition of functions, allowing for more flexible and expressive programming patterns.

Get ready for an exciting dive into the world of inbuilt higher-order functions like map, filter, forEach, and reduce in my upcoming article! ๐Ÿš€ Stay tuned for a coding adventure and let's make programming an absolute delight! ๐ŸŒˆ๐ŸŒŸ Happy coding! ๐ŸŽ‰.

Follow me!!!

Linkedin

Github

twitter

ย