Select Page

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 ect has certain costs associated. So first we know we are going to have a sandwich function which will always have the toppings and sandwich types, and each type of sandwich is going to have its own function.

``````Const toppingTotal = 1;

Return (toppingTotal + bread) + 2

}

Return (toppingTotal + bread) * 3

}

}

}
``````

## 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 scenes this is automatically providing the (toppingTotal + bread) -1 that is allocated when someone buys a Sweet Georgia sandwich as it is the sandwich of the day. So save a buck and write a higher order function.

👏

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!