Higher - Order Functions in JavaScript

Higher - Order Functions in JavaScript

An over-view of higher-order functions in JavaScript and how to use them

Higher order functions are a part of JavaScript you must have come across while learning JavaScript, you may have even used it without knowing.

This is a function that returns or accepts another function, it operates on other functions and even take them as arguments

Some advantage of Higher order functions are;

  • It allows you to write clean, simple and readable code.
  • with simple codes, you have fewer bugs.

JavaScript comes with built-in higher-order functions and we can also write our own higher order functions.

Map.
The map() method creates a new array by calling the callback function provided as an argument on every element in the input array. This method creates a new array and keeps the original array.

const nums = [5, 10, 15];                       
const newNums = 
nums.map( function (item) { return item * 2; 
}) ;

//this returns [25, 100, 225]

Filter.
This method creates a new array and fills it with elements that pass a test

  • Let’s say we have an array of people’s age and need to filter out those below 19 and return just those above 19.
const ages = [17, 18, 15, 20, 25, 30, 29]

const oldAges =
 ages.filter( function (age) { 
return age >= 20
 });

//this returns [20, 25, 30, 29]

Reduce.
This method returns a single output value. It executes the callback function on each member of the calling array. The reduce() method accepts two parameters

  • The reducer function
  • The initial value (optional)

The reducer function takes four arguments;

  • Accumulator
  • Current Value
  • Current Index (optional)
  • Source Array (optional)

The accumulator holds the callback’s return values while the Current Value refers to the element being processed in the array.

The initial value.
If an initial value is added, it will be used as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used as the original accumulator value.

const num = [1, 2, 3, 4];

const numSum =
mum.reduce (function 
(accumulator, currentValue) { 
return accumulator + currentValue
} ,5);

//this returns numSum = 15

An initial value was added which was 5. If you remove the initial value, it returns 10.

const num = [1, 2, 3, 4];

const numSum =
mum.reduce (function 
(accumulator, currentValue) { 
return accumulator + currentValue
});

//this returns numSum = 10

In conclusion, higher-order functions are powerful and makes writing codes simpler. These are prime examples of built-in higher-order functions and you can also write your own function.