Skip to content

Higher Order Functions

ParvinBDJ edited this page May 22, 2020 · 2 revisions

Higher-Order Functions research

A fast explanation for a higher-ordered function is: ‘A higher-order function is a function that takes a function as an argument, or returns a function.’ (Elliott, E. | 2019, 10 januari).

Besides the fact that higher-order functions can return a function. In this article I am going to be focussing on a higher-order function that takes a function as an argument. Some functions are sort of ‘built-in’ in Javascript, which are: map, reduce, and filter. I am going to cover this HOF.

Map()

The map() method takes an array and puts it through a function (made by the user). Then makes a new array that has been through the given function. For example:

var arr = [1, 4, 9, 16];
// the array

var map = arr.map(function(x){       //calling .map and giving it a function
 x = x * 2;        // what has to happen in the function
 return x
});
console.log(map);
//outcome: Array: [2, 8, 18, 32]

You see here how a function takes a function as an argument, a.k.a. higher-order function.

Reduce()

The reduce() method takes each element in an array and runs a function with it (that you give). So that there is one outcome. For example:

const arr = [1, 2, 3, 4];
function reducer(accumulator, currentValue){
return accumulator + currentValue;
};
// here we make the value that the .reduce needs to work

// 1 + 2 + 3 + 4
console.log(arr.reduce(reducer));
// outcome: 10

// 5 + 1 + 2 + 3 + 4
console.log(arr.reduce(reducer, 5));
// outcome: 15

You see how reduce takes all the element and trows it in a function (which you provide).

Filter()

Filter creates a new array with all the elements which went through the ‘test’ (which you provide). For example:

var words = ['hallo', 'yo', 'ey', 'fakka', 'hoi'];
// the array that you are going to use
var result = words.filter(function(word){
return word.length <= 2;
});
// filtering word that are smaller or equal to 2 letters
console.log(result);
// outcome: Array [“yo”, “ey”]

You see here that you can filter whatever you want if you write a correct function for it.

Sources

Clone this wiki locally