what is Higher Order Functions?

  • a function that take function as argument or return a function is known as Higher order Function.
  • use of Higher order function in functional programming

const area = function (radius){
	return Math.PI * radius * radius;
}

const calculate = function (arr, logic){
	const output = [];
	for(let i=0; i<arr.length; i++){
		output.push(logic(arr[i]))
	}
}

console.log(calculate([1,2,3,4], area));

Map, filter and reduce

Map

// used for array transformation
const arr = [1, 2, 3, 4, 5];

const double = arr.map((item) => 2 * item);

const binary = arr.map((item) => item.toString(2));

Filter

const arr = [1, 2, 3, 4, 5, 6, 7];

const odd = arr.filter((item) => item % 2);

const even = arr.filter((item) => item % 2 === 0);

Reduce

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

const sum = arr.reduce(function (accumulator, current) {
  accumulator += current;
  return accumulator;
}, 0); // 0 for accumulator as default value