Console Learner — An interactive JavaScript course.


3.7 Higher-order Functions

A higher-order function either takes a function argument and/or returns a function value. It is an important concept from the functional programming paradigm.

>>>
function map(fn, arr) {
    var res = [];
    for (var item of arr) {
        res.push(fn(item));
    }
    return res;
}

  
The map() function is an example of a higher-order function. The fn argument is a function that is called for each value in arr.
>>>
map(parseInt, ['0', '1.5', -3, ''])
[0, 1, -3, NaN]
By using map(), the for loop is hidden and the intent of the code can become clearer.
>>>
var factorThree = (val) => val * 3;


  
>>>
map(factorThree, [0, 1.5, -3])
[0, 4.5, -9]
The map() function can be used for many purposes. In this case a multiplication of all values in an array becomes concise.
>>>
function factor(num) {
    return (val) => val * num;
}

  
But wait... There is more! What if we create a factor() function that returns a function that multiplies with any given number...
>>>
map(factor(3), [0, 1.5, -3])
[0, 4.5, -9]
...so that our previous code can be expressed like this?
>>>
map(factor(4), [0, 1.5, -3])
[0, 6, -12]
It is now trivial to multiply by any other factor. Using higher-order functions allows for powerful and concise expressions with a high degree of code reuse.
>>>

The console allows you to interact with the course material and examples. Use the following keys:

A special logging function is also available:


Need more magic? Check out the other developer tools on this site.