Click on text below to jump to specific point in the video
We will see the basic function in its natural habitat. This is a simple function. Not all programs can do this: create an anonymous function and assign it to a variable. We can pass it around like any other value.
What are higher order functions good for?For composition. Since you can take a function and put it into another function, it allows us to compose a lot of small functions into bigger functions. Let us look at an example.
Probably the most basic and useful higher order function is the filter function. It is a function on the array that accepts another function as its argument, which you can use to return a new filtered version of the array.
We see a list of animals. We want to filter out the dogs.
Normal way of for loop to do this
Lets rewrite using filter functionLets have a look at this. Filter accepts one argument, another function. Functions you send into other functions are called callback
functions.Filter will loop through each item in the array and for each item, it will apply the callback function. It will expect the filter function to return either true or false to decide whether or not the new item should be in the array. Once done, it will return the filtered array.
Notice that the sample using filter is a lot less code than for loop. Its because we are actually writing less code, less logic.
Creating a new array is handled inside the filter function. The callback function and the filter function lock into each other - they are composable.
Lets break out the callback into a variable. By defining the isDog function. We can use it for other things. We could pass it to reject (not in JS natively, but is there in other libraries like underscore).
Next time I will talk about map and reduce. Video outline created using VideoJots