Learning JavaScript? Topic: Higher Order Functions

Learning JavaScript? Topic: Higher Order Functions

Subscribe to my newsletter and never miss my upcoming articles

Functional Programming

The concept of Higher Order Functions was derieved from Functional programming. Functional Programming in JavaScript is a form of programming where functions can be passed to other functions as parameters or be returned as values.

Higher Order Functions

This way of programming gave birth to what is known as HOF(Higher Order Functions). Which are simply functions that accept parameters as functions OR return them as values. Can be one or the other doesnt have to be both.

Functions as First Class Citizens

This is only possible because JavaScript treats functions like First Class Citizens (must be nice 😊). Meaning that functions can be

  • Stored in variables
  • Passed as arguments
  • Used in an array
  • Returned from a function
  • Assigned as an object property

Just like you will do if you were using other first class citizens like strings, numbers, booleans, objects and arrays.

Example of how the above will look like with functions

Functions stored in a variable

const add = function(x) {
  return x + x;
}// prints 10
add(5);

Functions passed as arguments

function operation(x,y,action){
    return action(x,y);
}

function add(x,y) {
    return x + y
}

function substract(x,y) {
    return x - y;
}

console.log(operation(2,3, add)); //prints 5
console.log(operation(4,3, substract)); //prints 1

Functions used in an array

coffee = [
  {
    name: 'Capuccino',
    sugar: 2
  },
  {
    name: 'Black Coffee',
    sugar: 0
  }
];

//function
getCoffee = function(coffee) {
     return coffee.name;
}
coffeeNames = [];

for (let i = 0; i < coffee.length; i++) {
  const name = getCoffee(coffee[i]);

  coffeeNames.push(name);
}

console.log(coffeeNames);
// ["Capuccino", "Black Coffee"]

Functions returned from another function

function storeValue(n) {
    let local = n;
    // this is a shorthand for writing 
    // return function () { return local };
    return () => local;
}

let val1 = storeValue(1);
let val2 = storeValue(2);

console.log(val1());
// → 1
console.log(val2());
// → 2

Functions assigned as an object property

const obj = {
    name : "Omotola",
    height : "5'4ft",
    operation : () =>
    {
        return `${obj.name} is ${obj.height} tall` 
    } 
}

console.log(obj.operation()); //Omotola is 5'4ft tall

Because of how JavaScript allows for us developers to use functions we can appreciate the importance of HOF because it encourages reusability. Without this concepts functions that we love and use like map, filter and reduce will not exsist. So its typically advisable to

MAP()

The map function accepts a function which is called on every item in an array. So in this case we have called a function that adds each item in the array by two. Since the map function cannot change the original array (arr1), we have created another variable to store the new array(arr2) in it.

This promotes reusability because instead of writing a loop everytime you want to perform an action on each item of your array you can just call the map function to do the same thing.

Visual representation of what the map function does

(image credit from here )

FILTER()

In this example we use the HOF filter which returns an object to the array fullAge if the value of age in the object satisfies the condition age greater than or equal 18. Meaning the filter function only returns values to the new array if the condition is true.

Can you see how many lines of code we remove when using a higher order function compared to writing it from scratch? Hope you are sold now!

Visual representation of this

(image credit from here )

REDUCE()

With the reduce function it accepts two arguments. The first argument being the a function and the second argument the initial value for the accumulator, in this case it is 0. The function passed normally takes two arguments which is the initial value or accumulator and the currentValue that is in the array. In this case since we have passed an initial value of 0 the accumulator starts from zero and adds the current value of the index untill the sum of the array is achieved.

A visual representation of this

(image credit from here )

We can see how the use of such functions makes our code alot readable and more efficient. The use of HOF like reduce, map, filter etc is not only reserved for JavaScript inbuilt functions. You can also create yours. Assuming you want to write a function that allows your dog perform two actions one after the other, we can write this function like this

Where dogActions is a Higher Order function because it accepts a function named callback which is called if the first parameter value matches the smiley. Below the HOF you can see the implementation of the function we are working with, this function is passed in two different calls to the dogActions function. Making out code more readable and functional.

And there you have it, hope your knowledge on this topic has been reinforced!

Please if you liked this post react to it 😊 so that other people can see it, leave a comment 💭 below if you have any questions and finally share it with someone! Thank you for reading up till this point

#javascript#2articles1week#programming-blogs#functional-programming#es6
 
Share this
Proudly part of