If you’re like me, you grew up using the classic for-loop in js.
I have no complaints. It works well, is easy to implement, easy to follow and your code is readable.
Why would anyone not use a for-loop you might ask?
Because it breaks the simple constructs of our highly endeared D.R.Y(Do Not Repeat Yourself) Principle!
Okay so maybe I do have one complaint.
Think about it, how many times do you make a for-loop with the same variable names?
Enter Higher Order Functions.
A higher-order function is a function that is passed another function as a parameter.
Essentially it reduces the amount of boilerplate needed in your code.
We will be looking at the two common implementations of higher-order functions.
Observe the vanilla syntax.
Long, Ugly, inefficient, and prone to syntactical errors.
Let me show you the same function with the map method.
It does the same thing, just without the headache of managing all the dependent variables. So much easier!
Next stop we have filter. Which ummm filters an array. Yes, I know very descriptive.
Being a higher-order function it takes a function as a parameter. This function will be used to determine what is returned. Below I have made a simple reusable function to return all even numbers from an array.
As you can see the function we pass in is `(num) => num % 2 ===0`
It's easier to think of these pass-in functions in terms of sudo-code.
If you are stuck I recommend saying this aloud ^
Here is the same function using a for-loop.
Again a headache.
higher-order functions are not a one size fits all alternative. rather they are a way to save yourself some typing. They are a very useful tool to have in your belt. It is up to the discretion of you the discerning developer to implement when needed.