Software Development Exam  >  Software Development Notes  >  JavaScript for Web Development  >  Higher Order Functions in JavaScript

Higher Order Functions in JavaScript | JavaScript for Web Development - Software Development PDF Download

Introduction

In JavaScript, functions are considered first-class citizens, which means they can be assigned to variables, passed as arguments to other functions, and even returned as values from other functions. Higher order functions take advantage of this feature by accepting functions as arguments or returning functions as results. They provide a powerful tool for writing concise and reusable code in web development.

In this article, we will explore higher order functions in JavaScript and understand how they can be used to enhance our web development projects. We will cover various concepts, provide examples, and explain their outputs to help beginners grasp the topic.

Understanding Higher Order Functions

A higher order function is a function that either takes one or more functions as arguments or returns a function as its result. These functions can be used to abstract and generalize common patterns in our code.

Example 1: Passing a Function as an Argument

Let's start with a simple example to illustrate the concept of passing a function as an argument.

function greet(name) {

  return `Hello, ${name}!`;

}


function greetUser(greetingFunction) {

  const userName = "John";

  return greetingFunction(userName);

}


console.log(greetUser(greet));

Output:

Hello, John!

In the code above, we have two functions: 'greet' and 'greetUser'. The 'greetUser' function takes a 'greetingFunction' as an argument and calls it with a specific name. In this example, we pass the 'greet' function as an argument to 'greetUser'. As a result, 'greetUser' invokes the 'greet' function, passing the name "John," and returns the greeting.

Example 2: Returning a Function

Now, let's see an example where a higher order function returns another function.

function multiplyBy(factor) {

  return function (number) {

    return factor * number;

  };

}


const multiplyByTwo = multiplyBy(2);

console.log(multiplyByTwo(5));

Output:

10

In the code above, the 'multiplyBy' function returns an anonymous function that multiplies a given number by the 'factor' passed as an argument to 'multiplyBy'. We assign the result of 'multiplyBy(2)' to the variable 'multiplyByTwo'. When we call 'multiplyByTwo(5)', it multiplies 5 by 2 and returns the result.

Common Use Cases

Higher order functions can be used in various scenarios to enhance our web development projects. Here are a few common use cases:

1. Callback Functions

Callback functions are a prevalent use of higher order functions in JavaScript. They allow us to pass a function as an argument to another function and have it called later at a specific event or condition. This pattern is widely used in asynchronous programming, event handling, and AJAX requests.

function fetchData(url, callback) {

  // Simulating an asynchronous request

  setTimeout(function () {

    const data = { name: "John", age: 25 };

    callback(data);

  }, 2000);

}


function processData(data) {

  console.log("Received data:", data);

}


fetchData("https://example.com/api", processData);

Output:

Received data: { name: 'John', age: 25 }

In the above example, the 'fetchData' function simulates an asynchronous request and passes the received data to the 'callback' function. We define the 'processData' function as the callback and pass it to 'fetchData'. After a delay of 2 seconds, the 'fetchData' function invokes the 'processData' function with the received data.

2. Array Manipulation

Higher order functions can also be used for array manipulation tasks, such as filtering, mapping, and reducing data.

const numbers = [1, 2, 3, 4, 5];


// Filtering even numbers

const evens = numbers.filter(function (number) {

  return number % 2 === 0;

});


console.log(evens); // [2, 4]


// Mapping numbers to their squares

const squares = numbers.map(function (number) {

  return number ** 2;

});


console.log(squares); // [1, 4, 9, 16, 25]


// Reducing numbers to their sum

const sum = numbers.reduce(function (accumulator, number) {

  return accumulator + number;

}, 0);


console.log(sum); // 15

In the code above, we demonstrate how higher order functions like 'filter', 'map', and 'reduce' can be used on arrays. The 'filter' function filters the numbers array for even numbers, the 'map' function calculates the square of each number, and the 'reduce' function adds up all the numbers to calculate the sum.

Sample Problems

Problem 1: Calculate the average of an array of numbers.

function calculateAverage(numbers) {

  const sum = numbers.reduce(function (accumulator, number) {

    return accumulator + number;

  }, 0);


  return sum / numbers.length;

}


const numbers = [1, 2, 3, 4, 5];

console.log(calculateAverage(numbers));

Output:

3

Problem 2: Find the longest word in an array of strings.

function findLongestWord(words) {

  const longestWord = words.reduce(function (longest, word) {

    return word.length > longest.length ? word : longest;

  }, "");


  return longestWord;

}


const words = ["apple", "banana", "grapefruit", "orange"];

console.log(findLongestWord(words));

Output:

grapefruit

Conclusion

Higher order functions provide a powerful tool for writing flexible and reusable code in JavaScript. By accepting functions as arguments or returning functions as results, we can abstract common patterns and enhance our web development projects. Whether it's working with callbacks, manipulating arrays, or solving complex problems, higher order functions are an essential part of a JavaScript developer's toolkit. With practice and exploration, you will become comfortable using higher order functions to write efficient and elegant code.

Remember, mastering higher order functions requires practice and familiarity with JavaScript's functional programming concepts. Keep experimenting, exploring documentation, and working on coding exercises to strengthen your understanding and skills.

The document Higher Order Functions in JavaScript | JavaScript for Web Development - Software Development is a part of the Software Development Course JavaScript for Web Development.
All you need of Software Development at this link: Software Development
51 videos|28 docs|12 tests

Top Courses for Software Development

51 videos|28 docs|12 tests
Download as PDF
Explore Courses for Software Development exam

Top Courses for Software Development

Signup for Free!
Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
10M+ students study on EduRev
Related Searches

Summary

,

mock tests for examination

,

Sample Paper

,

video lectures

,

Higher Order Functions in JavaScript | JavaScript for Web Development - Software Development

,

ppt

,

Free

,

Important questions

,

study material

,

pdf

,

Extra Questions

,

Exam

,

MCQs

,

shortcuts and tricks

,

past year papers

,

Objective type Questions

,

practice quizzes

,

Previous Year Questions with Solutions

,

Higher Order Functions in JavaScript | JavaScript for Web Development - Software Development

,

Semester Notes

,

Higher Order Functions in JavaScript | JavaScript for Web Development - Software Development

,

Viva Questions

;