js higher order function examples

Example 1: higher order functions javascript

/* Answer to: "higher order functions javascript" */

/*
  Higher order functions are functions that operate on other
  functions, either by taking them as arguments or by returning
  them.
  
  In simple words, A Higher-Order function is a function that
  receives a function as an argument or returns the function as
  output.
  
  For example; Array.prototype.map, Array.prototype.filter and
  Array.prototype.reduce are some of the Higher-Order functions
  built into the language.
  
  For more information, go to:
  https://blog.bitsrc.io/understanding-higher-order-functions-in-javascript-75461803bad
*/

Example 2: js higher order functions

// function that adds 2 numbers
function add(number1, number2){
	return number1 + number2;
}

// function that multiplies 2 numbers
function multiply(number1, number2){
	return number1 * number2;
}

// higher order function: takes 2 arguments and a function in this case
function calc(number1, number2, fn){
	return fn(number1, number2);
}

// this is how you would use it
calc(10, 2, add); // you can also use 'multiply' or any other function

// output: 12

Example 3: js higher order function examples

function copyArrayAndManipulate(array, instructions) {
  const output = []
  for(let i = 0; i < array.length; i++) {
    output.push(instructions(array[i]))
  }
  return output
}

function multiplyBy10(input) {
  return input * 10
}

copyArrayAndManipulate([1, 2, 3], multiplyBy10)

Example 4: higher order function in javascript

let total = 0, count = 1;
while (count <= 10) {
  total += count;
  count += 1;
}
console.log(total);

Tags:

Misc Example