Functional Programming Methods in Javascript

Functional programming Methods in js is one of the main focus nowadays and it should be it makes our lives so much easier as we don't have to use loops to do some basic things like transform elements in a list, filter a list, etc. Let's see what functional programming actually is.

forEach

let list = [1,2,3,4,5,6]//Non fp way
for(let i=0;i<list.length;i++){
console.log(list[i]*2)
}
//fp way
list.forEach(elem => console.log(elem*2))

Here you can see the effort and line of code we saved using just one line of code. What actually forEach does is it iterates through a list and give you it’s an element on which you can perform any operation.

Note: forEach does not return anything.

Map

//non fp way
let result = [];
for(let i=0;i<list.length;i++){
result.push(list[i]*2)
}
console.log(result);
//fp way
let result_fp = list.map(elem => elem*2)
console.log(result_fp)

Here you can see the actual benefits of using fp here you can see how much effort it has saved. The map does a pretty similar thing to forEach but the difference lies is that for every iteration that map produces it returns a result and that iterative result forms a new list.

Filter

//non fp way
result = []
for(let i=0;i<list.length;i++){
if(list[i]%2 === 0){result.push(list[i])}
}
console.log(result);
//fp way
result_fp = list.filter(elem => elem%2 === 0)
console.log(result_fp)

okay, so the filter is a little complicated as it relies on true and false statements. let me put it this way if you return true it will add that item to the list otherwise it will not. Basically, when we were checking in filter for every even number it is giving a truthy value, hence adding that no. to the list and if that number gives falsy value it will skip that element.

Reduce

//non fp way
result = 0
for(let i=0;i<list.length;i++){
result = result + list[i];
}
console.log(result);
//fp way
result_fp = list.reduce((sum,elem) => sum + elem ,0)
console.log(result_fp)

Okay so let see what happened step by step. While other methods are independent of their previous iterations here it is dependent. What actually reduce does is takes 2 params one its initial iterative value and other is a function which has arguments both initial iterative value and element and here it returns the sum of previous iterative value and element till the whole iteration is complete.

I hope this article will help regarding better understanding of fp methods. I am attaching the repl link for a better understanding.

Just a curious dev who writes when gets bored of work life