DEV Community

Anastasia Bennett
Anastasia Bennett

Posted on

Keeping Order with Higher Order Functions in Javascript

If you're like me, when you're first learning to code you may get caught up writing a lot more than you have to. This can get a little overwhelming, especially if we need to perform a certain functionality multiple times. Luckily, when it comes to great programming, simplicity is key. Higher-order functions are not only handy, but necessary for writing complex functionality with more concise code.

Higher-order functions are ones that either take in one or more functions as arguments and/or return a function as a result. Once a function like that is implemented, it can replace a really common functionality or be used to simplify a bulky code.

For instance, let's look at .forEach() :

This is a really useful higher-order function because it gives us a quick way to loop over arrays and apply a function to each element.

Let's write it out to see what it does, then we'll take a look at it in action.

    //forEach takes in an array and a callback function//
    function forEach(array, func) {

        //then it loops over the array//
        for (let i = 0; i < array.length; i++) {

            //and it calls the given function on each 
              element//
            //the callback func takes in the current element, 
              index, and array//
            func(array[i], i, array);
        }
    };
Enter fullscreen mode Exit fullscreen mode

forEach doesn't return anything, it simply performs an action on each element in the array. You can write your own version of this to include objects too, but the native version only traverses arrays.

Native forEach also uses dot notation to invoke it, like this:

    let numbers = [1, 2, 3];

    numbers.forEach((num) => {console.log(num + 1)})

    //output: 2
    //output: 3
    //output: 4
Enter fullscreen mode Exit fullscreen mode

The array is to the left of the dot, so the only argument left to pass in is the callback function.

So when we need to perform an action on each element in an array, which comes up quite a bit, instead of writing an entire for-loop, we can just use forEach!

An even more helpful higher-order function is .map() . This one loops over an array (or an object if you write it yourself) and applies a function to each element, just like forEach, but it returns an array containing the result of each function call.

     //just like forEach, map takes an array and a function
     function map(array, func) {

          //let's make a variable to store our new array//
          let result = [];

          //then we loop over the array, like before//
          for (let i = 0; i < array.length; i++) {

               //this time we'll push each function call into 
                 our new array//
               result.push(func(array[i], i, array));
          }

          //then we return our final array
          return result;
     };
Enter fullscreen mode Exit fullscreen mode

Map can really come in handy if we need to alter the data inside a collection. Say we have a list of names and we need them to be capitalized. We can use .map() to avoid having to write out everything we did above.

     let names = ["symone", "summer", "blair", "trina"]

      //the names array is to the left of the dot, so in the 
      parameters all we need to do is define the callback 
      function//

     let capitalizedNames = names.map((name) => {
         return name[0].toUpperCase() + name.slice(1);
     })

     console.log(capitalizedNames);
     //output: ["Symone", "Summer", "Blair", "Trina"]
Enter fullscreen mode Exit fullscreen mode

Higher-order functions make our lives as programmers so much easier by turning what could be chunks of repeated code into just a line or two. They make our code so much faster to write by doing the bulk of the work for us, and a lot easier to read by keeping it hidden!

Where have you been reusing code that could be turned into a higher-order function instead?

Top comments (0)