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 Commands

Laravale commands #Check route list php artisan route:list #Check upload files links php artisan storage:link #Check database connected or not php artisan db #Make Request file php artisan make:request YourNameRequest #Make Controller #(In this statement you used -r -> resources and -m -> model. It will create CustomersController and Customers Model files) php artisan make:controller CustomersController -r -m Customers #Make Resource file php artisan make:resource CustomersResource #To check migration files status that those files are running or not with below commands php artisan migrate:status #To check if there is any pending migrate files to run #(also this command shows us the mysql query before running migration file) php artisan migrate --pretend #To make a database table (in this example Products name as taken) php artisan make:migration create_products_table #To create a Request file php artisan make:request StoreProductRequest php artisan make:request Up

Mysql columns creation in laravel

List of columns  $table->id(); // increment value $table->string('title')->comment('this is blog title'); $table->string('slug')->unique(); $table->text('short_desc'); $table->longText('description'); $table->boolean('is_published')->default(false); $table->integer('min_of_read')->nullable(true); $table->enum('status', ['Active', 'Inactive']); $table->float('discount'); $table->smallInteger('type_id'); $table->date('start_date')->nullable(); $table->timestamps(); $table->foreign('created_by')->references('id')->on('users'); // introducing foreign key $table->unsignedBigInteger('user_id'); //? $table->decimal('latitude', 9, 6)->nullable(true); // Let's say you want starting value from 1000 $table->id()->from(1000); // increment value start from 1000 ->nullabl

React Advanced JSX

 class vs className This lesson will cover more advanced JSX. You’ll learn some powerful tricks and some common errors to avoid. Grammar in JSX is mostly the same as in HTML, but there are subtle differences to watch out for. The most frequent of these involves the word class. In HTML, it’s common to use class as an attribute name: <h1 class = "big" > Title </h1> In JSX, you can’t use the word  class ! You have to use  className  instead: <h1 className = "big" > Title </h1> This is because JSX gets translated into JavaScript, and  class  is a reserved word in JavaScript. When JSX is  rendered , JSX  className  attributes are automatically rendered as  class  attributes. Self-Closing Tags Another common JSX error involves  self-closing tags . What’s a self-closing tag? Most HTML elements use two tags: an  opening tag  ( <div> ), and a  closing tag  ( </div> ). However, some HTML elements such as  <img>  and  <input>  u