WHAT ARE HIGHER ORDER METHODS?
Higher order array methods in javascript are built-in methods that take a function as an argument or return a function as a result.
In Javascript we use many higher order methods that helps in several array manipulation tasks. Few of commonly used array methods are:
- forEach()
- map()
- filter()
- reduce()
- find()
- findIndex()
- some()
- every()
- sort()
- flatmap()
In this blog I am going to discuss about the most commonly asked higher order methods that are map(), reduce() and filter().
map()
map() higher order method is used to map through an array and return a new array by performing some operation.
Syntax
map((value)=>{
})
map((value,index)=>{
})
map((value,index,array)=>{
})
Example
let a=[1,2,3,4]
let a1=a.map((value)=>{
console.log(value)
return value+2
})
let a2=a.map((value,index)=>{
console.log(value,index)
return value+2
})
let a3=a.map((value,index,array)=>{
console.log(value,index,array)
return value+2
})
filter()
filter() method is used to filter an array with values that passes the test.
Syntax
filter((value)=>{
})
filter((value,index)=>{
})
filter((value,index,array)=>{
})
Example
let a=[28,96,15,1,3,5]
let a1=a.filter((value)=>{
return value>10
})
console.log(a1)
reduce()
reduce() method is used to reduce an array into a single value. reduce() method usually takes two parameters as an argument.
Syntax
reduce((h1,h2)=>{
})
Example
let a=[1,4,5,3,7]
let a1=a.reduce((h1,h2)=>{
return h1+h2
})
Higher order methods are powerful tools that allow more readable, concise and function-style programming. map(), reduce() and filter() methods are some basic and more important methods which are usually asked in beginners interview.
Top comments (1)
Great post, Shreeprabha! This is a very clear and concise explanation of some of the most important higher-order array methods in JavaScript. The examples really help illustrate how map(), filter(), and reduce() work in practice. Looking forward to more posts like this. Thanks for sharing! 😊