Javascript has provided many built-in functions to complete a particular task. But if we try to solve any program normally with those built-in functions, the code may not be concise. Javascript has also provided some inbuilt higher-order functions. These higher-order functions decrease the length of the code, increase the readability and simplify the accessibility. Some of the higher-order functions are maps, filters and reduce. Let's discuss filter higher-order function.
Example
when there is no higher-order functions program code may take more number of steps in total. In the following example, a new array is taken, even though the provided array is enough to complete the task. A for-loop, which is unnecessary in case of higher-order functions, is taken to loop through the array.
<html> <body> <script> const name = []; var persons = [ { name: 'Frodobaggins'}, { name: 'aragorn'}, { name: 'gandalf'}, { name: 'pippin'}, { name: 'nazgul'}, ]; for(let i = 0; i < persons.length; i++) { if(persons[i].name.length > 6) { name.push(persons[i]); } } document.write(JSON.stringify(name)); </script> </body> </html>
Output
[{"name":"Frodobaggins"},{"name":"aragorn"},{"name":"gandalf"}]
Example
In the following example, a higher-order function filter is used. Comparing to the above example, the following example has occupied less number of lines of code. Here no new array is taken and also no for-loop is used.
<html> <body> <script> const persons = [ { name: 'Frodobaggins'}, { name: 'aragorn'}, { name: 'gandalf'}, { name: 'pippin'}, { name: 'nazgul'}, ]; const name = persons.filter(person => person.name.length > 7); document.write(JSON.stringify(name)); </script> </body> </html>
Output
[{"name":"Frodobaggins"}]