Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 3289

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 26, 20242024-11-26T01:21:11+00:00 2024-11-26T01:21:11+00:00

Understanding Higher-Order Funtions

  • 61k

Introduction

In this article I will be going over what higher-order functions are, how to use them, and why they are important.
 

Variables, Values, and Functions

Before that, let's refresh the basics. You can assign values to a variable:

const x = 5; const y = "hello"; const z = {object: true}; 
Enter fullscreen mode Exit fullscreen mode

You can also pass in values into a function:

function foo(bar){     console.log(bar); } foo("hello world"); 
Enter fullscreen mode Exit fullscreen mode

bar is a parameter, and you can refer to that value passed inside the function.

Okay, that's pretty simple, so what?
 

Functions As Values

In JavaScript, we can use functions as values! We can assign it to a variable, pass as a function, or return from a function.

function hello(){     console.log("hello world"); } const x = hello;  //notice that it's not hello() x(); //you can call the variable since it holds function 
Enter fullscreen mode Exit fullscreen mode

A function can even be returned as a value:

function one(){     console.log(1) } function two(){     return one } const x = two; const y = two(); 
Enter fullscreen mode Exit fullscreen mode

 

Higher-Order Functions And Callback Functions

Functions are values just like a number or string. If you've heard that functions are first-class citizens in JavaScript, this is what it means.

function callbackFunction(){     console.log("hello world"); } function higherOrderFunction(fn){     fn();  //we can call the function that we passed in! } higherOrderFunction(callbackFunction);  //notice that it's not callbackFunction() 
Enter fullscreen mode Exit fullscreen mode

Just like values, we can refer to the argument passed into the function (higherOrderFunction). Since it's a function, we can call it like a regular function using parenthesis ().

The function being passed as an argument is often called a callback function, while the function accepting the callback function is called a higher-order function . It can be also considered a higher-order function if it only returns a function.

So to review:

  • Functions can be assigned to variables
  • Functions can be passed as an argument to other functions
  • Functions can return other functions

 

  • A function that is passed to a function is called a callback function
  • A function that accepts a callback function is a higher-order function
  • A function that returns a function is also a higher-order function

 

Example

Let's say I wanted create a function to sort my book. I want to sort it in alphabetical order by title. The structure would look something like this:

function sortBooks(books){     ... // sort books in alphabetical order by title } const books = [book1, book2, book3]; sortBooks(books); 
Enter fullscreen mode Exit fullscreen mode

Perfectly normal. But now, I want the option to sort it by author. I'm going to have to make some changes:

function sortByTitle(books) {...}; function sortByAuthor(books) {...};  function sortBooks(books, sortBy){     if(sortBy === "title") {     return sortBooks(books) // sort books in alphabetical order by title     } else if (sortBy === "author") {     return sortByAuthor(books) // sort books in alphabetical order by author     } } const books = [book1, book2, book3]; sortBooks(books, "title"); sortBooks(books, "author"); 
Enter fullscreen mode Exit fullscreen mode

If I wanted many different ways to sort, this might get messy. A good way to solve this problem is by passing in a function

function sortByTitle(books) {...} function sortByAuthor(books) {...}  function sortBooks(books, sortingFunction){     return sortingFunction(books); }  const books = [book1, book2, book3]; sortBooks(books, sortByTitle); sortBooks(books, sortByAuthor); 
Enter fullscreen mode Exit fullscreen mode

Now, the function is more composable. I can use whatever sorting function I want and I don't have to impose those functions upon anyone using the package or library.

You might be wondering why we need a separate sortBooks function for that. Can't we do this?

function sortByTitle(books) {...}; function sortByAuthor(books) {...};  const books = [book1, book2, book3]; sortByTitle(books); sortByAuthor(books); 
Enter fullscreen mode Exit fullscreen mode

Indeed you can, but when dealing with more complex systems, it's less reusable. We might have a structure that handles many methods and data.

class LibrarySystem(){     this._sortStrategy;     function setSortStrategy(sortingFunction) {         this._sortStrategy= sortingFunction;     }     function sortBooks(books) {         return this._sortStrategy(books); //reuse sort     }     function fetchBooks(bookSource){         const books = fetchBooks(bookSource);         return this._sortStrategy(books); //reuse sort     }     function combineBookLists(books1, books2){         const books = books1.concat(books2);         return this._sortStrategy(books); //reuse sort     }     //...etc } 
Enter fullscreen mode Exit fullscreen mode

This is actually called the Strategy Pattern, and is very commonly used to make interchangeable parts of a code.
 

More Examples

Event Listeners

You might have heard about event listeners. In order to make a button work, you have to bind a function to it. In JavaScript, we bind functions to the DOM by adding event listeners.

function sayHello(){     console.log("hello"); } const button = document.getElementById("btn"); // gets button button.addEventListener("click", sayHello); 
Enter fullscreen mode Exit fullscreen mode

addEventListener is a higher-order function because it takes in a function. This is a very common way to bind a function to an event.

Array Methods

In JavaScript, there are array methods forEach,reduce, filter, and map. They are higher-order functions that allow you to modify arrays using your own callback functions.

function capitalizeNames(item){     return item.toUpperCase(); } const books = ["Hyperion", "Do Androids Dream of Electric Sheep?", "A Song of Ice and Fire"]; books.map(capitalizeNames); 
Enter fullscreen mode Exit fullscreen mode

Timers

setTimeout and setInterval will run a function in relation to time. In order for them to work you need to pass in a function.

function sayHello(){     console.log("hello"); } setTimeout(sayHello, 1000); setInterval(sayHello, 500); 
Enter fullscreen mode Exit fullscreen mode

 

Go Do Stuff

Higher-order functions let you create composable and reusable code, and many interfaces often use them. You can use them as values just like any other values.

If you know how to pass in a number or string, then you know how to pass in a function. If you know how to return an object or boolean, then you know how to return a function. It's easier than you think, so go ahead and start trying it yourself!

function doStuff(you){     you() } doStuff(you) 
Enter fullscreen mode Exit fullscreen mode

go do stuff

javascriptprogrammingtutorialwebdev
  • 0 0 Answers
  • 1 View
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.