
Higher Order Functions in JS
Now this is nothing new and fresh but for me it really was an ah ha moment when you are building out an application there are times when having a pre set function that is going to do some work later on. Now I am familiar with objects, methods, ect but sometimes a function within a function just feels right.
Lets Make Sandwiches With JavaScript
In this example let’s say we are making 3 different types of sandwiches, but depending on the type of sandwich there is going to be a different cost associated.
Sandwich types:
Dutch Munch, Tater Island, and Sweet Georgia
Each of these are going to have an automatic calculation associate with them due to the ingredients.
Dutch munch = toppings + 2
Tater Island = toppings * 3
Sweet Georgia = topping – 1
Bread cost = 1$ per slice
How Can A Function Help
Knowing that the cost of toppings plus the type of sandwich up charge how can we do this?
Let’s say that we need to have each topping cost $1 and each piece of bread used is also $1, but then each type of sandwich due to the cost of meat, special
Const toppingTotal = 1;
Cost bread =1;
Function dutchMunch(toppingTotal, bread){
Return (toppingTotal + bread) + 2
}
Function taterIsland(toppingTotal, bread){
Return (toppingTotal + bread) * 3
}
Function sweetGeorgia(toppingTotal, bread){
Return (toppingTotal + bread) -1
}
Function sandwich(toppingTotal,bread,sandType){
Return sandType(toppingtoal, bread);
}
Higher Order Function What!
So what is a Higher Order Function… basically, just a function that can take other functions as inputs. This helps in this situation as when we are creating the orders the input can be as follows.
sandwich(3,3,sweetGeorgia);
Behind the
👏
What we did here is the beauty of JS and that is using a higher order function that is taking inputs from other functions to get the job done!