Prerequisite
- Functions are first-class citizens in JavaScript, which means that we can take a function and pass it as an argument to a function.
- A function which is been passed as an argument is known as Callback Function.
- A function which takes another function as an argument or returns a function is called Higher Order Function.
INPUT -->
function cb(){
console.log("JavaScript");
}
function ho(cb){
cb();
}
OUTPUT -->
JavaScript
In the above piece of code, function cb()
is a callback function which is passed as an argument to the function ho()
which is a higher-order function.
[].map()
, [].filter()
and [].reduce()
are higher-order function which take a callback function as an argument. All three functions are part of the array prototype in javascript which means that they must be called directly on an array.
1. [].map()
[].map()
is used to transform an array. Transform means to change each and every value of the array and get a new array out of it.[].map()
will run the passed callback function on every element of the array and return a new array with transformed values.
INPUT -->
const arr = [ 1, 6, 3, 6, 0, 8];
//Double the value of each element in an array.
function getDouble(item){
return item * 2;
}
const output1 = arr.map(getDouble);
console.log(output1);
//Convert each number of an array into its binary form.
function getBinary(item){
return item.toString(2);
}
const output2 = arr.map(getBinary);
console.log(output2);
OUTPUT -->
- [ 2, 12, 6, 12, 0, 16 ]
- [ '1', '110', '11', '110', '0', '1000' ]
2. [].filter()
[].filter()
is used to filter an array. Filter means to remove elements which do not satisfy the condition.[].filter()
will take a conditional callback function and return a new array from the given array with elements for which the condition wastrue
.
INPUT -->
const arr = [ 8, 3, 1, 7, 6, 9, 1, 8, 0, 5];
//Filter out even numbers from an array.
function isOdd(item){
return item%2;
}
console.log(arr.filter(isOdd));
//Filter out elements with values less than 4.
const output = arr.filter(item => item > 4)
console.log(output);
OUTPUT -->
- [ 3, 1, 7, 9, 1, 5 ]
- [ 8, 7, 6, 9, 8, 5 ]
3. [].reduce()
[].reduce()
is used when we need to take all elements of an array and come up with a single value out of them.- For example, finding the sum of all the elements in an array, finding the maximum number in an array etc.
INPUT -->
const arr = [ 8, 3, 1, 7, 6, 9, 1, 8, 0, 5];
//Find the sum of all the elements in an array.
const sumOfArray = arr.reduce(function(acc, curr){
acc = acc + curr;
return acc;
}, 0);
console.log(sumOfArray);
//Find the element with the maximum value in an array.
const max = arr.reduce(function(acc, curr){
if(curr > acc){
acc = curr;
}
return acc;
}, 0)
console.log(max);
OUTPUT -->
- 48
- 9
To further read about this topic in-depth, do check out the resource: