Pradeep Pandey
Pradeep Pandey

@Div_pradeep

14 Tweets 1 reads Dec 23, 2022
What are Higher Order Functions in JavaScript?
A Thread๐Ÿงต๐Ÿ‘‡๐Ÿป
๐–๐ก๐š๐ญ ๐š๐ซ๐ž ๐‡๐ข๐ ๐ก๐ž๐ซ ๐Ž๐ซ๐๐ž๐ซ ๐…๐ฎ๐ง๐œ๐ญ๐ข๐จ๐ง๐ฌ ?
โ†’ Normally when you hear the word functions you think of a regular function that takes an input, does some magic, and returns some value as output like this.
๐„๐ฑ๐š๐ฆ๐ฉ๐ฅ๐ž:
Now what's the difference between that normal function and a higher order function ?
โ†’ A higher order function is a function that takes in a function as an argument or returns a function.
The functions that operate with another function are known as Higher order Functions.
Examples:
โžŠ ๐ฆ๐š๐ฉ()
โž‹ ๐Ÿ๐จ๐ซ๐„๐š๐œ๐ก()
โžŒ ๐ซ๐ž๐๐ฎ๐œ๐ž()
โž ๐Ÿ๐ข๐ฅ๐ญ๐ž๐ซ()
โ†’ Now all these higher order functions apply to arrays so we'll make a dummy array with some numbers to practice using those functions.
nums = [2,4,6,8,3,5]
๐Ÿ: ๐“๐‡๐„ ๐Œ๐€๐() ๐Œ๐„๐“๐‡๐Ž๐ƒ
โ†’ This method iterates over an array and takes in one parameter that represents the element in the current iteration.
โ†’ A common use for this function is when we iterate over some response from an API and need to log or render the elements on our frontend.
โ†’ You don't need to say return as the function returns a value by default.
๐Ÿ: ๐“๐‡๐„ ๐…๐Ž๐‘๐„๐€๐‚๐‡() ๐Œ๐„๐“๐‡๐Ž๐ƒ
โ†’ As the name implies, this function also iterates over an array but the difference is that map() returns a new array meanwhile forEach() returns undefined.
๐Ÿ‘: ๐“๐‡๐„ ๐‘๐„๐ƒ๐”๐‚๐„ ๐Œ๐„๐“๐‡๐Ž๐ƒ
โ†’ This method takes a callback that takes two parameters, one that represents the element from the last iteration and the other is the current element of the iteration.
โ†’ Use case is finding the sum of the array elements by adding the previous element to the current element like so:
4: ๐“๐‡๐„ ๐…๐ˆ๐‹๐“๐„๐‘() ๐Œ๐„๐“๐‡๐Ž๐ƒ
โ†’ We use this method to filter out desired elements as per a condition we specify.
โ†’ let say you only want the odd numbers or even numbers or want numbers higher or lower than a specific value,
โ†’ if that's the case then this method is the right tool.
That's a wrap!
If You liked this thread.
1. Follow @Div_pradeep for more such content around web development, resources, tips, and cheatsheet.
2. RT the first tweet to share it with other people.
I appreciate it!
Thanks for reading.

Loading suggestions...