DEV Community

loading...
Cover image for Higher Order Function Examples

Higher Order Function Examples

jps27cse profile image Jack Pritom Soren ・1 min read

Example-1 without higher order function

var number = [1,2,3];
var result =[];

for (let i = 0; i < number.length;i++)
{
    result.push(number[i]*2);
}

console.log(result);
Enter fullscreen mode Exit fullscreen mode

Example-1 with higher order function

var number = [1,2,3];

var result = number.map((item)=>{
    return item * 2;
})

console.log(result);
Enter fullscreen mode Exit fullscreen mode

Example-2 without higher order function

var players =
[
    {
        name: 'A',
        avg: 33.2
    },
    {
        name: 'B',
        avg: 37.3 
    },
    {
        name: 'C',
        avg: 38.32
    },
    {
        name: 'D',
        avg: 40.76
    }
];

var UpdateResult = [];

for(var i = 0; i <players.length; i++)
{
    if(players[i].avg >= 37)
    {
       UpdateResult.push(players[i]);
    }
}

console.log(UpdateResult);
Enter fullscreen mode Exit fullscreen mode

Example-2 with higher order function

var players =
    [
        {
            name: 'A',
            avg: 33.2
        },
        {
            name: 'B',
            avg: 37.3
        },
        {
            name: 'C',
            avg: 38.32
        },
        {
            name: 'D',
            avg: 40.76
        }
    ];

var UpdateResult = players.filter((player) => player.avg >= 37);

console.log(UpdateResult);
Enter fullscreen mode Exit fullscreen mode

Example-3 without higher order function

var arr = [1, 2, 3, 4];

function getArraySum(array) {
    var total = 0;
    for (var i = 0; i < array.length; i++) {
        total += array[i];
    }
    return total;
}

var result = getArraySum(arr);

console.log(result)

Enter fullscreen mode Exit fullscreen mode

Example-3 with higher order function

var arr = [1, 2, 3, 4];

var total = arr.reduce((sum, item) => {
    return result = sum + item;
})

console.log(result);

Enter fullscreen mode Exit fullscreen mode

Discussion (4)

pic
Editor guide
Collapse
slex1onemusdy profile image
Mustafa

I really enjoyed it during the read time. Thanks for the content! It was really beneficial for me.

Collapse
jps27cse profile image
Jack Pritom Soren Author

You are welcome!

Collapse
florianwoelki profile image
Florian Woelki

Would be awesome, if there is an example for reduce

Collapse
jps27cse profile image
Jack Pritom Soren Author

I'll add this ,,, thanks for your suggestion