Skip to content
Akin C edited this page Aug 29, 2017 · 17 revisions

Welcome to the Javascript-higher-order-functions- wiki!

Higherorder functions in Javascript are known as callback functions. They are functions which are used as an argument in another function or return a function as a result. An simple example could be as follows:

function mainFunction(a, b, callback)
{
    var result = callback(a, b);
	
    return result; 
}

function callbackFunction(x, y)
{
   return x * y;
}

//Call
console.log(mainFunction(2, 2, callbackFunction));//Outputs 4

One thing which is important to understand is that callbackFunction could be defined differently (e.g. return x + y) and it will still work fine. Following this insight, High-order functions gives the developer a certain flexibility to change or write callback functions as they need it whithin a specific frame.

Another way is to write a callback function as an anonymous function, like this:

function mainFunction(a, b, callback)
{
    var result = callback(a, b);
	
    return result; 
}

//a = 2 and b = 2
var output = mainFunction
(
	2,
	2,
	function(x,y)
	{
		return x * y;
	}

)

console.log(output)//Outputs 4

The anonymous version could be often seen in jQuery.

Javascript offers already useful Higher-order functions. The following functions listed are used in this project:

  1. forEach()
  2. map()
  3. filter()
  4. reduce()
  5. reduceRight()
  6. sort()

The first five ( sort() excluded ) have some parameters in common which could be used in a callback function:

  • currentValue : Gives access to the current value in an array
  • index : Gives access to the index for the current value in an array
  • array : The array which is processed by the High-order function

Content

The user interaction part should look like the content as seen below by starting "index.html" in a web browser.

ERROR: No image found!

The user input seen in the picture above is the one which is used for all examples.

  • Button "FOREACH":
  • Button "MAP":
  • Button "FILTER":
  • Button "REDUCE":
  • Button "REDUCE RIGHT":
  • Button "SORT":

The colored areas are just for a better readability in the wiki and are not part of the content. To use the project just download the files and execute "index.html". Note that all files should be placed in the same folder so that the functionality of the code is guaranteed.

STILL IN WORK!

Clone this wiki locally