Skip to main content

HIGHER-ORDER FUNCTIONS IN JS

 Introduction

We are often unaware of the number of assumptions we make when communicating in our native languages. If we told you to “count to three,” we would expect you to say the numbers “one”, “two”, and “three”. We assumed you would know to start with “one” and end with “three”. With programming, we need to be more explicit with our directions to the computer. Here’s how we might tell the computer to “count to three”:

for (let i1; i <= 3; i++) {
  console.log(i);
}

When we speak to other humans, we share a vocabulary that provides quick ways to communicate complicated concepts. When we say the word “bake”, it calls to mind a familiar subroutine— preheating an oven, putting something into an oven for a set amount of time, and finally removing it. This allows us to abstract away a lot of the details and communicate key concepts more concisely. Instead of listing all those details, we can say, “We baked a cake,” and still impart all that meaning to you.

In this lesson, we’ll learn how to use “abstraction” in programming by writing functions. In addition to allowing us to reuse our code, functions help to make clear, readable programs. If you encounter countToThree() in a program, you might be able to quickly guess what the function does without having to stop and read the function’s body.

We’re also going to learn about a way to add another level of abstraction to our programming: higher-order functionsHigher-order functions are functions that accept other functions as arguments and/or return functions as output. This enables us to build abstractions on other abstractions, just like “We hosted a birthday party” is an abstraction that may build on the abstraction “We made a cake.”



JavaScript functions behave like any other data type in the language; we can assign functions to variables, and we can reassign them to new variables.

Below, we have an annoyingly long function name that hurts the readability of any code in which it’s used. Note: If the below function’s syntax feels unfamiliar, revisit the arrow functions exercise to refresh your knowledge on ES6 arrow notation.

const announceThatIAmDoingImportantWork = () => {
    console.log("I’m doing very important work!");
};

Let’s pretend this function does important work and needs to be called repeatedly. To rename this function without sacrificing the source code, we can re-assign the function to a variable with a suitably short name:

const busyannounceThatIAmDoingImportantWork;

busy(); // This function call barely takes any space!

busy is a variable that holds a reference to our original function. If we could look up the address in memory of busy and the address in memory of announceThatIAmDoingImportantWork they would point to the same place. Our new busy() function can be invoked with parentheses as if that was the name we originally gave our function.

Notice how we assign announceThatIAmDoingImportantWork without parentheses as the value to the busy variable. We want to assign the value of the function itself, not the value it returns when invoked.

In JavaScript, functions are first class objects. This means that, like other objects you’ve encountered, JavaScript functions can have properties and methods.

Since functions are a type of object, they have properties such as .length and .name, and methods such as .toString(). You can see more about the methods and properties of functions in the documentation.

Functions are special because we can invoke them, but we can still treat them like any other type of data. Let’s get some practice doing that!


As you know, a parameter is a placeholder for the data that gets passed into a function. Since functions can behave like any other type of data in JavaScript, it might not surprise you to learn that functions can accept other functions as parameters. A higher-order function is a function that either accepts functions as parameters, returns a function, or both! We call functions that get passed in as parameters callback functions. Callback functions get invoked during the execution of the higher-order function.

When we invoke a higher-order function, and pass another function in as an argument, we don’t invoke the argument function. Invoking it would evaluate to passing in the return value of that function call. With callback functions, we pass in the function itself by typing the function name without the parentheses:

const higherOrderFuncparam => {
  param();
  return `I just invoked ${param.name} as a callback function!`
}

const anotherFunc = () => {
  return 'I\'m being invoked by the higher-order function!';
}

higherOrderFunc(anotherFunc);

We wrote a higher-order function higherOrderFunc that accepts a single parameter, param. Inside the body, param gets invoked using parentheses. And finally, a string is returned, telling us the name of the callback function that was passed in.

Below the higher-order function, we have another function aptly named anotherFunc. This function aspires to be called inside the higher-order function.

Lastly, we invoke higherOrderFunc(), passing in anotherFunc as its argument, thus fulfilling its dreams of being called by the higher-order function.

higherOrderFunc(() => {
  for (let i0; i <= 10; i++){
    console.log(i);
  }
});

In this example, we invoked higherOrderFunc() with an anonymous function (a function without a name) that counts to 10. Anonymous functions can be arguments too!

Let’s get some practice writing higher-order functions.


Great job! By thinking about functions as data, and learning about higher-order functions, you’ve taken important steps in learning to write clean, modular code that takes advantage of JavaScript’s flexibility.

Let’s review what we learned in this lesson:

  • Abstraction allows us to write complicated code in a way that’s easy to reuse, debug, and understand for human readers.

  • We can work with functions the same way we work with any other type of data, including reassigning them to new variables.

  • JavaScript functions are first-class objects, so they have properties and methods like any other object.

  • Functions can be passed into other functions as parameters.

  • A higher-order function is a function that either accepts functions as parameters, returns a function, or both.


Comments

Popular posts from this blog

Laravel form validations

 Laravel Validations: List of types "first_name" => 'required|alpha:ascii|min:3|max:100',// alpha:ascii (only accepts a-z) "middle_name" => 'string', "last_name" => 'required|string', "email" => 'required|email|unique:users,email', "password" => 'required|string|confirmed', "sex" => 'required|string', "phone_no" => 'required|string', "account_type" => 'required|string', "dob" => 'required|date_format:d-m-Y', // date with format "nationality" => 'required|string', "company" => 'required|string', "company_sector" => 'required|string', "company_address" => 'required|string' "bank_account_no" => 'required|min_digits:3|max_digits:5', "role" => 'required|in:admin,editor,viewer', ...

React Js Commands

React JS Commands and Useful purposes  To Install react app: npx create-react-app app-name To Install react app: npx create-react-app . To check npm version: npm --version Inside that directory, you can run several commands:   npm start     Starts the development server.   npm run build     Bundles the app into static files for production.   npm test     Starts the test runner.   npm run eject     Removes this tool and copies build dependencies, configuration files     and scripts into the app directory. If you do this, you can’t go back! node -v (To check node version) The latest recommended command to create a new React app is: npx create-react-app@latest my-app Replace my-app with your desired project name. This approach uses the latest version of Create React App and works if Node.js (version 14+) and npm (version 5.2+) are installed Modern Alternatives If you prefer a faster, lighter setup, many developers n...

Advanced Objects Introduction in JS

  Advanced Objects Introduction Remember, objects in JavaScript are containers that store data and functionality. In this lesson, we will build upon the fundamentals of creating objects and explore some advanced concepts. So if there are no objections, let’s learn more about objects! In this lesson we will cover these topics: how to use the this keyword. conveying privacy in JavaScript methods. defining getters and setters in objects. creating factory functions. using destructuring techniques. The this Keyword Objects are collections of related data and functionality. We store that functionality in methods on our objects: const goat = {    dietType : 'herbivore' ,    makeSound () {      console . log ( 'baaa' );   } }; In our  goat  object we have a  .makeSound()  method. We can invoke the  .makeSound()  method on  goat . goat . makeSound (); // Prints baaa Nice, we have a  goat  ob...