{"id":4289,"date":"2022-09-24T15:10:15","date_gmt":"2022-09-24T20:10:15","guid":{"rendered":"https:\/\/www.becomebetterprogrammer.com\/?p=4289&#038;preview=true&#038;preview_id=4289"},"modified":"2022-09-24T15:17:17","modified_gmt":"2022-09-24T20:17:17","slug":"javascript-higher-order-functions-a-guide-with-examples","status":"publish","type":"post","link":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/","title":{"rendered":"JavaScript Higher-Order Functions: A Guide with Examples"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Functions are one of the fundamental building blocks in Javascript. A function is a set of statements that perform a task or calculate a value. They come in handy as they simplify our program&#8217;s structure, readability, and reusability by abstracting the implementation of a particular algorithm. As a functional language, Javascript supports the concept of high-order functions to abstract the purpose of a particular function.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>A high-order function in Javascript is a function that,<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Takes a function as an argument. Or<\/strong>,<\/li><li><strong>Returns a function as a value after it is done with computation. Or,<\/strong><\/li><li><strong>Performs both operations &#8211; takes a function as an argument and returns a function.<\/strong><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Why should a function take another function as a parameter? Why would a function return another function as a value? To answer all the questions you might have in mind, this post will give an in-depth guide on Javascript high-order functions. However, first, have a refresher on the basic concepts of functional programming.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_84 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\"><p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<\/div><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Functional_Programming\" >Functional Programming<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Functions_as_First-Class_Citizens\" >Functions as First-Class Citizens<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Higher-Order_Functions\" >Higher-Order Functions<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Functions_That_Take_Other_Functions_as_Arguments\" >Functions That Take Other Functions as Arguments<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Functions_That_Return_Other_Functions\" >Functions That Return Other Functions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Functions_That_Take_Other_Functions_as_Arguments_and_Return_Other_Functions\" >Functions That Take Other Functions as Arguments and Return Other Functions<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Higher-Order_Array_Methods\" >Higher-Order Array Methods<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Arraymap\" >Array.map()<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Normal_Way\" >Normal Way<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Using_Arraymap\" >Using Array.map()<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Arrayfilter\" >Array.filter()<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Normal_Way-2\" >Normal Way<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Using_Arrayfilter\" >Using Array.filter()<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Arrayreduce\" >Array.reduce()<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Normal_Way-3\" >Normal Way<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Using_Arrayreduce\" >Using Array.reduce()<\/a><\/li><\/ul><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Advantages_of_Higher-Order_Functions\" >Advantages of Higher-Order Functions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Functional_Programming\"><\/span>Functional Programming<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Developers use many programming patterns, and functional programming is just one of them. Other patterns include <a href=\"https:\/\/www.techtarget.com\/searchapparchitecture\/definition\/object-oriented-programming-OOP\" target=\"_blank\" rel=\"noopener\">object-oriented programming<\/a>, <a href=\"https:\/\/www.geeksforgeeks.org\/differences-between-procedural-and-object-oriented-programming\/\" target=\"_blank\" rel=\"noopener\">procedural programming<\/a>, etc.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">One of the significant ideas behind Functional programming is <a href=\"https:\/\/brilliant.org\/wiki\/lambda-calculus\/\" target=\"_blank\" rel=\"noopener\">Lambda Calculus<\/a> &#8211; a comprehensive computing model. Together with Functional Programming, Lambda Calculus could be said to represent the following concepts:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The composition and use of functions can completely solve&nbsp;any computable task.<\/li><li>A function abstracts the complexity of an algorithm and takes a value, and returns another value. When working with pure functions, the output will always be the same when given the same input and has no side effects. Check out our post &#8211; &#8220;<a href=\"https:\/\/www.becomebetterprogrammer.com\/javascript-pure-and-impure-functions\/\">A Complete Guide to Pure and Impure Functions in JavaScript.<\/a>&#8220;<\/li><li>Functions are also values. They can be used as inputs for other functions and returned as values by other functions. You will learn more about this in the next section when looking at &#8220;functions as first-class citizens.&#8221; This is one of the features that enable Javascript to implement higher-order functions<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Functions_as_First-Class_Citizens\"><\/span>Functions as First-Class Citizens<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">You might have probably heard a popular phrase by developers stating, &#8220;functions are first-class citizens in Javascript.&#8221; That&#8217;s because functions in Javascript can operate like any other data type, such as a string, object, or array.<\/p>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\">Have a look at the interesting piece of code below. Here, the function <code>favoriteSport()<\/code> is operating as an object.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function favoriteSport(){\n}\n\nfavoriteSport()\n\n\/\/Here, you add properties to the function\nfavoriteSport.outdoor = \"Handball\"\nfavoriteSport.indoor = \"Monopoly\"\n\nconsole.log(favoriteSport.outdoor)\nconsole.log(favoriteSport.indoor)\n\n\/*Output:\nHandball\nMonopoly<\/code><\/pre>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\">From the code above, you will notice that the properties <code>outdoor<\/code> and <code>indoor<\/code> are added to the function once it&#8217;s invoked. You can then access these properties as you would on an object.<\/p>\n\n\n\n<p class=\"has-luminous-vivid-amber-background-color has-background wp-block-paragraph\"><strong>Note<\/strong>: Although passing properties to a function is possible, it is not verified as a good programming practice.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">As a summary of this section,<strong> below are some of the operations you can perform with functions as first-class citizens.<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Assign functions to a variable<\/strong><\/li><li><strong>Use functions as input to another function or return a function as the &#8220;return value&#8221; of another function.<\/strong><\/li><li><strong>Store functions in arrays.<\/strong><\/li><li><strong>Set function as&nbsp;object properties.<\/strong><\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">When you look at all the above features concerning functions as first-class citizens, then look at the high-order function definition given above &#8211; you will notice these are the things that make it possible to implement high-order functions in Javascript.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">With that in mind, you can dive into the main topic of today.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Higher-Order_Functions\"><\/span>Higher-Order Functions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">As stated in the definition, <strong>higher-order functions take functions as arguments or return functions as the &#8220;return value&#8221; or perform both operations<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Below are a few examples to give you a solid understanding of higher-order Javascript functions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Functions_That_Take_Other_Functions_as_Arguments\"><\/span>Functions That Take Other Functions as Arguments<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Take a look at the code snippet below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const numbers = &#91;1, 2, 3, 4, 5, 6];\n\nfunction parentFn(arr, fn) {\n\tfor (let i = 0; i &lt; numbers.length; i++) {\n\t\tfn(arr&#91;i]);\n\t}\n}\n\nlet doubledNums = &#91;];\n\nfunction childFn(x) {\n\tdoubledNums.push(x * 2);\n}\n\nparentFn(numbers, childFn);\n\nconsole.log(\"Initial Array: \",numbers)\nconsole.log(\"Doubled Array: \",doubledNums);\n\n\/*Output:\nInitial Array:  &#91; 1, 2, 3, 4, 5, 6 ]\nDoubled Array:  &#91; 2, 4, 6, 8, 10, 12 ]<\/code><\/pre>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\">In the above example, <code>parentFn()<\/code> is the higher order function. It takes two arguments &#8211; an array (<code>arr<\/code>) and a function (<code>fn<\/code>). It loops through each element in the array and uses the <code>fn()<\/code> logic to manipulate these items. In this case, <code>fn()<\/code> is invoking the <code>childfn()<\/code> function which multiplies every array item by two.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Functions_That_Return_Other_Functions\"><\/span>Functions That Return Other Functions<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Do you have a good understanding of JavaScript Currying? If not, check out this comprehensive post &#8211; <a href=\"https:\/\/www.becomebetterprogrammer.com\/javascript-currying\/\">A Complete Guide to JavaScript Currying: What Does it Mean?<\/a> You will have a better understanding of what we will look at in this example.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Take a look at the code below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>function favoriteFruits(fruitOne) {\n  return function (fruitTwo) {\n    return function (fruitThree) {\n      return \"John Loves \" + fruitOne +\", \" + fruitTwo +\" and \" + fruitThree;\n    };\n  };\n}\n\nconsole.log(favoriteFruits(\"mangoes\")(\"bananas\")(\"oranges\"))\n\/*Output:\nJohn Loves mangoes, bananas and oranges<\/code><\/pre>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\">Here, the <code>favoriteFruits()<\/code> function is a higher-order function that returns other functions which require other arguments. For example, it first returns a function that requires you to pass the <code>fruitTwo<\/code> argument; then, it returns a third function that requires you to pass a <code>fruitThree<\/code> argument. The last function will then return the actual value. In this case, it&#8217;s a string.<\/p>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\">To invoke this function and pass arguments to the other functions, you will use the syntax <code>favoriteFruits(argumentOne)(argumentOne)(argumentOne)<\/code>. Please, check that post on <a href=\"https:\/\/www.becomebetterprogrammer.com\/javascript-currying\/\">Javascript Currying<\/a> to understand this concept in-depth.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Functions_That_Take_Other_Functions_as_Arguments_and_Return_Other_Functions\"><\/span>Functions That Take Other Functions as Arguments and Return Other Functions<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In the previous two sections, you have looked at functions that either take a function as an argument or return a function as the return value. Below is a function that performs both operations &#8211; it takes a function as an argument and returns a function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const friends = &#91;\"John\",\"Jane\",\"Erick\",\"June\"]\n\nfunction functionOne(arr, fn){\n  for (let i = 0; i &lt; friends.length; i++){\n    fn(arr&#91;i])\n  }\n  return function(school){\n    console.log(\"We all went to \"+school+\" university\")\n  }\n}\n\nfunction functionTwo(x){\n  console.log(\"My friend is: \"+ x)\n}\nfunctionOne(friends,functionTwo)(\"Aghakan\")\n\n\/*Output:\nMy friend is: John\nMy friend is: Jane\nMy friend is: Erick\nMy friend is: June\nWe all went to Aghakan university<\/code><\/pre>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\">In the above code, <code>functionOne()<\/code> is a higher-order function. It takes a function (<code>functionTwo<\/code>) as an argument and returns another function (<code>function(school)<\/code>). You will also notice a concept of currying incorporated in this particular example.<\/p>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\"><code>functionOne()<\/code> has a &#8220;for loop&#8221; that iterates through the <code>friends<\/code> array and fetches each item. Each array item is passed to the <code>fn()<\/code> function, which invokes <code>functionTwo()<\/code> and prints the friend&#8217;s name.<\/p>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\">After the &#8220;for loop&#8221; exits, <code>functionOne<\/code> will return a function (<code>function(school)<\/code>) which is involved when calling <code>functionOne()<\/code> as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>functionOne(friends,functionTwo)(\"Aghakan\")<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Higher-Order_Array_Methods\"><\/span>Higher-Order Array Methods<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Most of the built-in Javascript methods used to manipulate strings, DOM, and arrays are higher-order Javascript methods. This section will focus on the arrays. An array is a single variable that can store other elements, which include numbers, strings, objects, or other arrays. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Below are some of the array methods which are, in fact, higher-order functions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Arraymap\"><\/span>Array.map()<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The map function takes a callback function as an argument. It iterates through each element in the array and invokes the callback function on the element. The return value of the callback function is stored in a new array.<\/p>\n\n\n\n<p class=\"language-javascript has-vivid-green-cyan-background-color has-background wp-block-paragraph\"><strong>Tip<\/strong>: The <code>Array.map()<\/code> method does not mutate the array upon which it is called. Instead, it creates a new array with values returned by the callback function.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Assume you have an array of three digits, and you want to multiply each digit by two. How would you go about it?<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Normal_Way\"><\/span>Normal Way<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Normally, this is how you would write your code.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const nums = &#91;10, 20, 30];\nlet doubledNums = &#91;];\nfunction multiplyNums(arr) {\n\tfor (let i = 0; i &lt; arr.length; i++) {\n\t\tdoubledNums.push(arr&#91;i] * 2);\n\t}\n}\nmultiplyNums(nums);\nconsole.log(doubledNums);\n\n\/*Output:\n&#91; 20, 40, 60 ]<\/code><\/pre>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\">Here, you are using a &#8220;for loop&#8221; to iterate through every single element in the array, multiplying the element by two and pushing it to the <code>doubledNums<\/code> array. Although you achieved what you wanted, there is a much simpler method.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_Arraymap\"><\/span>Using Array.map()<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Below is a code snippet you could use to achieve the same results using the map method.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const nums = &#91;10,20,30]\n\nlet doubledNums = &#91;];\nnums.map((item)=&gt; doubledNums.push(item*2));\n\nconsole.log(doubledNums);\n\n\/*Output:\n&#91; 20, 40, 60 ]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here, you will have used less code, which is easy to read and debug.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Arrayfilter\"><\/span>Array.filter()<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\">The <code>array.filter()<\/code> method is a higher-order function that takes a callback function as an argument. Like the map method, the <code>array.filter<\/code> iterates an array fetching each element and passing it to the callback function. If the element passes the condition in the callback function, it is stored in a new array.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Assume you had an array of student objects shown below, and you need to filter the students pursuing &#8220;Law.&#8221; How would you go about it?<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const students =&#91;\n  {name:\"John\", course:\"Medicine\"},\n  {name:\"Jane\", course:\"Law\"},\n  {name:\"Erick\", course:\"Law\"},\n  {name:\"June\", course:\"Medicine\"},\n]<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Normal_Way-2\"><\/span>Normal Way<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Normally, this is how you would write your code using the &#8220;for loop&#8221; statement.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let lawStudents=&#91;]\nfunction filterStudents(arr){\n  for (let i = 0; i &lt; students.length; i++){\n    if(arr&#91;i].course === \"Law\"){\n      lawStudents.push(arr&#91;i].name)\n    }\n  }\n}\nfilterStudents(students)\nconsole.log(lawStudents)<\/code><\/pre>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\">Here, you use a &#8220;for loop&#8221; to iterate the array and fetch elements. Each element is then passed to the &#8220;if statement,&#8221; and if it passes the condition, it pushes the name property to the <code>lawStudents[]<\/code> array<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_Arrayfilter\"><\/span>Using Array.filter()<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\">With <code>array.filter<\/code> method, you will write less code that is easy to read and debug.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let lawStudents = students.filter(function(value){\n  return value.course === \"Law\"\n})\n\nconsole.log(lawStudents)\n\n\/*Output:\n&#91; { name: 'Jane', course: 'Law' },\n{ name: 'Erick', course: 'Law' } ]<\/code><\/pre>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\">Here, the <code>student.filter()<\/code> method iterates through the <code>students<\/code> array and passes each element to the callback function. This function uses a condition to check which students pursue law and if it&#8217;s true, that student is added to a new array. This new array is then assigned to the <code>lawStudents<\/code> variable.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Arrayreduce\"><\/span>Array.reduce()<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\">The <code>array.reduce<\/code> is an interesting array method and will always come in handy in most projects.  If you are not well versed with this method, checkout the post &#8211; <a href=\"https:\/\/www.becomebetterprogrammer.com\/javascript-array-reduce\/\">How to use Array Reduce in JavaScript: A Complete Guide<\/a>.<\/p>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\">As the name suggests, the <code>array.reduce<\/code> method reduces a function to a single value. When compared to the <code>map()<\/code> or the <code>filter()<\/code> methods, the <code>reduce()<\/code> method is a relatively complex higher-order function. This method accepts two arguments.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>An initial value<\/li><li>A callback function<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The callback function in turn also takes a couple of arguments.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Accumulator<\/li><li>Current value<\/li><li>Current index<\/li><li>Source Array<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Assume you had an array of student&#8217;s marks as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const studentMarks =&#91;40,45,37,25,55,65]<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Normal_Way-3\"><\/span>Normal Way<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Normally, this is how you would probably write the code to add all the array elements.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>let totalMarks = 0\n\nfor (let i =0; i &lt; studentMarks.length; i++){\n  totalMarks += studentMarks&#91;i]\n}\n\nconsole.log(totalMarks)\n\n\/*Output:\n267<\/code><\/pre>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\">Here, the &#8220;for loop&#8221; is iterating through the array and adding each element to the <code>totalMarks<\/code> variable.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_Arrayreduce\"><\/span>Using Array.reduce()<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"language-javascript wp-block-paragraph\">This is how you would solve the same problem using the <code>array.reduce()<\/code> method.<\/p>\n\n\n\n<pre class=\"wp-block-code language-javascript\"><code>const totalMarks = studentMarks.reduce(function(acc, value) {\n  return acc + value;\n});\nconsole.log(totalMarks);\n\n\/*Output:\n267<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Advantages_of_Higher-Order_Functions\"><\/span>Advantages of Higher-Order Functions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>They make code reusability much easier.<\/strong><\/li><li><strong>Higher-order functions are a&nbsp;great approach to separate and abstract program actions.<\/strong><\/li><li><strong>They enhance code simplicity. It&#8217;s much easier to read and debug code even for other developers.<\/strong><\/li><li><strong>Using higher-order functions save time in writing code, especially when working with complex applications.<\/strong><\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">That&#8217;s it! You now have an in-depth understanding of JavaScript Higher-Order Functions. From all the advantages listed above and those demonstrated in the example provided in this post, it&#8217;s time you start incorporating this concept into your projects. You can decide to use the higher-order built-in methods provided by Javascript or create your functions from scratch.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Was this article helpful? Do you have any suggestions or is there any additional information that you feel was left out?<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You can also share your thoughts by replying on Twitter of\u00a0<a href=\"https:\/\/twitter.com\/bbprogrammer\/status\/1459150572565798916\" target=\"_blank\" rel=\"noreferrer noopener\">Become A Better Programmer<\/a>\u00a0or to\u00a0<a href=\"https:\/\/twitter.com\/NetmattaTech\" target=\"_blank\" rel=\"noreferrer noopener\">my personal account<\/a>.<\/p>\n\n\n\n<figure class=\"wp-block-embed aligncenter is-type-rich is-provider-twitter wp-block-embed-twitter\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"twitter-tweet\" data-width=\"550\" data-dnt=\"true\"><p lang=\"en\" dir=\"ltr\">What are Higher-Order functions in <a href=\"https:\/\/twitter.com\/hashtag\/javascript?src=hash&amp;ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">#javascript<\/a>?<br><br>&quot;They take functions as arguments or return functions as the &quot;return value&quot; or perform both operations&quot;<br><br>This sounds hard to understand without seeing examples. Thankfully, <a href=\"https:\/\/twitter.com\/NetmattaTech?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">@NetmattaTech<\/a> has some to share<a href=\"https:\/\/t.co\/cocrE4yUpt\">https:\/\/t.co\/cocrE4yUpt<\/a><\/p>&mdash; Become A Better Programmer (@bbprogrammer) <a href=\"https:\/\/twitter.com\/bbprogrammer\/status\/1573768424647540737?ref_src=twsrc%5Etfw\" target=\"_blank\" rel=\"noopener\">September 24, 2022<\/a><\/blockquote><script async src=\"https:\/\/platform.twitter.com\/widgets.js\" charset=\"utf-8\"><\/script>\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>Functions are one of the fundamental building blocks in Javascript. A function is a set of statements that perform a task or calculate a value. They come in handy as they simplify our program&#8217;s structure, readability, and reusability by abstracting the implementation of a particular algorithm. As a functional language, Javascript supports the concept of &#8230; <a title=\"JavaScript Higher-Order Functions: A Guide with Examples\" class=\"read-more\" href=\"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/javascript-higher-order-functions-a-guide-with-examples\/\" aria-label=\"More on JavaScript Higher-Order Functions: A Guide with Examples\">Read more<\/a><\/p>\n","protected":false},"author":5,"featured_media":4365,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"nf_dc_page":"","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[16],"tags":[],"class_list":["post-4289","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript","generate-columns","tablet-grid-50","mobile-grid-100","grid-parent","grid-50"],"_links":{"self":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4289","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/comments?post=4289"}],"version-history":[{"count":5,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4289\/revisions"}],"predecessor-version":[{"id":4369,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/posts\/4289\/revisions\/4369"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media\/4365"}],"wp:attachment":[{"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/media?parent=4289"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/categories?post=4289"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.becomebetterprogrammer.com\/staging\/4563\/wp-json\/wp\/v2\/tags?post=4289"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}