JS functional programming - replace for loops

Today I want to share with you some basic yet powerful javascript programming method called functional programming. Functional programmings(FP) means coding in functions, duh. There are many advanced topics on FP, such as currying, pure FP, but today I just want to share some basic techniques of using map & filter to help our everyday code.

Below is an example, which we have an array of objects and we want to get the name of the people that are older than 18.

Tradional Way of using for loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const people = [
{name: 'Danny', age: 30},
{name: 'Calvin', age: 10},
{name: 'Mike', age: 4},
{name: 'Jeff', age: 50}
]
var adults = []
for(var i = 0; i < people.length; i++){
if(people[i].age > 18){
adults.push(people[i].name)
}
}
console.log(adults) // ["Danny", "Jeff"]

FP Way:

1
2
3
4
5
const isAdult = people => people.age > 18
const getName = people => people.name
const adults = people.filter(isAdult)
.map(getName)
console.log(adults) // ["Danny", "Jeff"]

Benefits of using FP is it makes code more sexy and make code more readable and more reusable.

References