Higher Order functions in JavaScript

Higher Order functions in JavaScript

In JavaScript functions are first-class-citizens this means in JavaScript functions behave like variables. therefore functions can be assigned to a variable or passed as an argument or can be returned by another function.

What is a Higher order function?

A function which takes another function as an argument or returns a function as an output from it , is known as higher order function.

// Function as a variable
const message = function () {
    console.log('we are learning Higher Order Functions')
}

message()
//Function returning another function
const greet = function (name) {
    return function (message) {
        console.log(`Hey! ${name}, ${message}`);
    }
}
const greetingInfo = greet('Lokesh');
greetingInfo("have a good day!")
//Function receiving antother function as an argument

const numbers = [ 2, 3, 4, 5, 6, 7, 8, 9, 10];

function filterNumbers(arr, callback) {
    const filteredNumber = [];
    for (let i = 0; i < arr.length; i++) {
        callback(arr[i]) ? filteredNumber.push(arr[i]) : null;
    }
    return filteredNumber;
}
function isOdd(number) {
    return number % 2 !== 0
}
function isEven(number) {
    return number % 2 === 0
}

console.log(filterNumbers(numbers, isEven));
console.log(filterNumbers(numbers, isOdd));

Common Higher Order Functions in JS

  • map( )

A map allows you to pass a function that applies to every element of an Array that is why we call it a higher-order function.

It returns a new array and does not change the original array.

map() Syntax :

arr.map(callback(currentElement))

Example 1 :

// multiplying each element by 2
const numbers = [2, 3, 4, 5, 6]
const result = numbers.map((number) => {
   return number * 2
})
console.log(result);
// [ 4, 6, 8, 10, 12 ]

Example 2 :

const users = [
  { firstName: "John", lastName: "doe" },
  { firstName: "Mike", lastName: "daniel" },
  { firstName: "Rova", lastName: "kurada" }
];

const usersFullName = users.map((user) => {
  return `${user.firstName} ${user.lastName}`
})
console.log(usersFullName);
// [ 'John doe', 'Mike daniel', 'Rova kurada' ]
  • filter( )

Filter is used to define a new array with elements from the initial array that match a specified condition.

arr.filter(callback(element))

Example 1:

const numbers = [2, 3, 4, 5, 6]

const evenNumbers = numbers.filter((number) => {
    return number % 2 === 0
})

console.log(evenNumbers)
// [ 2, 4, 6 ]

Example 2 :

const colors = ['blue','green','yellow','pink','orange']

const filteredColors = colors.filter((color)=>{
  return color.length>4
})

console.log(filteredColors);
// [ 'green', 'yellow', 'orange' ]
  • reduce( )

  1. reduce() function is used to reduce the array into a single value by performing any operation on to it. Reduce function does not change the original array elements.

  2. The reduce method takes in 2 parameters.

First one is a callaback function

  • accumulator: It accumulates the return values of the callback function, returned in the last calling of the function.

  • currentValue: It is the value of the current element.

Second one is a initial value, If we provide the initial value, indexing will begin from 0. Else from 1.

reduce ( ) syntax


array.reduce(callback(accumulator, currentValue), initialValue)

Example 1 :

const numbers = [2, 3, 4, 5, 6]

const sumOfNumbers = numbers.reduce((accumulator, currentValue) => {
    return accumulator + currentValue
})
//  2 + 3 +  4 + 5 + 6
console.log(sumOfNumbers)

Example 2 :

const expenses = [2100, 2900, 2700, 700, 1400];
const salary = 22000;

const remaining = expenses.reduce(
  (accumulator, currentValue) => accumulator - currentValue,
  salary
);
// 22000 - 2100 - 2900 - 2700 - 700 - 1400
console.log(remaining);

Conclusion

The advantages of Higher Order functions are abstraction, composition, code reusability and readability.

I hope this post will help you understand Higher order functions in JavaScript