Higher Order Functions VS Callbacks
Simply put a higher order function takes in a function or passes out a function.
In a higher order function, when one of the parameters passed in is a function, that function is a callback function because it will be called back and used within the higher order function.
In this example can you guess which function is the higher order one and which one is the callback?
The function copyStringAndManipulate is the higher order function because it takes in a function and the callback is makeUppercase because it is the function passed into copyStringAndManipulate. But even more the function copyStringAndManipulate has a higher philosophy. Would you agree that copyStringAndManipulate is on a higher level of thinking than makeUppercase? It’s more abstract it can be likened to making pea soup:
“Put 1 cup of dried peas per person into a container. Add water until the peas are well covered. Leave the peas in water for at least 12 hours. Take the peas out of the water and put them in a cooking pan. Add 4 cups of water per person. Cover the pan and keep the peas simmering for two hours. Take half an onion per person. Cut it into pieces with a knife. Add it to the peas. Take a stalk of celery per person. Cut it into pieces with a knife. Add it to the peas. Take a carrot per person. Cut it into pieces. With a knife! Add it to the peas. Cook for 10 more minutes.”
Per person: 1 cup dried split peas, half a chopped onion, a stalk of celery, and a carrot. Soak peas for 12 hours. Simmer for 2 hours in 4 cups of water (per person). Chop and add vegetables. Cook for 10 more minutes.
The second is shorter and easier to interpret. But you do need to understand a few more cooking-related words such as soak, simmer, chop, and, I guess, vegetable.
Why Use Higher Order Functions and Callbacks?
Higher order functions generalize your code. Using the above example we don’t need to write a ton of new code each time we want to manipulate a string all we need to do is pass it a new callback.
Lets say we want to add a dash between each element of the string.
We only need to create one new function addDash this saves us time and follows the all important DRY principle (Do not repeat yourself)
Using higher order functions and callbacks reduces complexity in your code. Reducing complexity minimizes bugs saving time. Saving time saves money and saving money increases the bottom line for stakeholders.