JavaScript Higher-order Functions.

JavaScript Higher-order Functions.

·

2 min read

What are Higher order Functions

A function that accepts and/or returns another function is called a higher-order function. It’s higher-order because instead of strings, numbers, or booleans, it goes higher to operate on functions.

Let's learn Higher order functions with some examples!

• forEach() method calls a function once for each element in an array, in order.

const companies = [
{name: 'Tesla', category: 'electric cars'},
{name: 'Amazon', category: 'ecom'},
{name: 'Google', category: 'search engine'},
]

//old for loop
for(let i = 0; i < companies.length; i++){
    console.log(companies[i].name)
}

//new higher order forEach
companies.forEach((company) => console.log(company.name))

• map() method calls the provided function once for each element in an array and returns it, in order.

const companies = [
{name: 'Tesla', category: 'electric cars'},
{name: 'Amazon', category: 'ecom'},
{name: 'Google', category: 'search engine'},
]

//method 1
const companyName1 = companies.map(function(company) { 
    return company.name;
})

//method 2
const companyName2 = companies.map((company) => company.name)

• filter() method creates an array filled with all array elements that pass a test.

const ages = [18, 21, 24, 26, 28, 31, 34]

//old way
let canDrink1 = [];
for(let i = 0; i < ages.length; i++){
    if(ages[i] >= 21){
        canDrink.push(ages[i])
    }
}

//new way
const canDrink2 = ages.filter(age => age>=21)

• sort() method sorts the items of an array.

const ages = [34, 26, 24, 21, 38, 31, 19]

const sortedAge = ages.sort((a, b) => a-b)
console.log(sortedAge)  //[19, 21, 24, 26, 31, 34, 38]

• reduce() method reduces the array to a single value.

const ages = [34, 26, 24, 21, 38, 31, 19]

let ageSum = 0
ageSum = ages.reduce((total, age) => total+age, 0)
console.log(ageSum)

Let's make them work in harmony!

const ages = [34, 26, 24, 21, 38, 31, 19]

const ageMethod = ages
                  .map(age => age*2) 
                  .filter(age => age>=40)
                  .sort((a, b) => a-b)
                  .reduce((total, age) => total + age, 0)

Hope you liked the blog, and if you did make sure you follow me on Twitter @Deveshb15 where I post similar content every day!

Did you find this article valuable?

Support Devesh's Blog by becoming a sponsor. Any amount is appreciated!