Higher Order Functions — Simplicity Is The Ultimate Sophistication

In both life and programming , simplicity and organization can assist you in creating clear goals, focusing on your actions and being more productive. One clear cut way to achieve this in Javascript is through higher order functions. A higher-order function is a function that can take another function as an argument, or that returns a function as a result. In Javascript, functions are “first-class”, which means they are treated as objects. This ability gives programmers great flexibility and power when it comes to functional programming. Below you can explore some well known higher order functions, and start your path to enlightenment.

Each — Executes function on each element in an array.

//Implementation
var each = function(collection, callback) {
for(var i = 0; i < collection.length; i++) {
callback(collection[i], i, collection);
}
}
//Example
let array = [1,2,3,4,5];
let addOne = each(array, function(element, index, array){
console.log(element + 1);
});
console.log(addOne);// logs 2,3,4,5,6

Map — Executes function on each element in an array and returns new array.

//Implementation
var map = function(collection, callback) {
let mapped = [];
for(var i = 0; i < collection.length; i++) {
mapped.push(callback(collection[i], i, collection));
}
return mapped;
}
//Example
let array = [1,2,3,4,5];
let addOne = map(array, function(element, index, array){
return element + 1;
});
console.log(addOne);// returns [2,3,4,5,6]

Filter — Executes function on each element and returns array of elements that evaluate to true.

//Implementation
var filter = function(collection, callback) {
let filtered = [];
for(var i = 0; i < collection.length; i++) {
if(callback(collection[i], i, collection)){
filtered.push(collection[i]);
}
}
return filtered;
}
//Example
let array = [1,2,3,4,5];
let even = filter(array, function(element, index, array){
return element % 2 == 0;
});
console.log(even); // returns [2,4];