javascript interactive

JavaScript Interactive — a console crash course


3.7 Higher-order Functions

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.

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(func, arr) {
    var res = [];
    for (var i = 0; i < arr.length; i++) {
        res.push(func(arr[i]));
    }
    return res;
}

  
The map() function is an example of a higher-order function. The func 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 syntax is hidden and the intent of the code becomes clearer.
>>>
function factorThree(val) { return 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 function (val) { return val * num; };
}

  
But wait... There is more! ... What if we create a factor() function that returns a new function that performs the multiplication for 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.
>>>

Index 1 2 3 4 5 6 7 8 9