Functional Programming
What?
Functions are first-class citizens.
- It can be assigned as variables,
- It can be assigned as property in objects,
- It can be assigned to arrays,
- It can pass as arguments to another function,
- It can be return from another functions. All we can say that something which can be done with variables can also with functions. That's why we call functions are first-class citizens.
Why FP Is Important?
Because for larger codebase, things become more difficult to handle like,
- you can't debug tons lines code easily,
- you can't share component separately,
- Testing become difficult,
- you can't understand code better,
To overcome from such problems we need to follow functional programming, that makes your Code clean from normal ones. The best thing about Functional Programming that, It provides abstractions that makes code understandable
Let me give you basic example of functional programming..
ex: functional programming
const number = [1,2,3,4,5,6,7,8,9];
const sum = arr => arr.reduce(((prev,curr) => prev+curr),0);
console.log(sum(number))
ex: simple programming
const number = [1,2,3,4,5,6,7,8,9];
let sum =0;
for(let i =0;i<number.length;i++){
sum = sum + number[i]
}
console.log(sum)
from above we can see clearly, that how efficient is functional programming with less code and better understandable with simple one. The main concept behind functional programming is convert codes into abstraction. so that there will be less bugs.
How to do FP?
Functional programming focus on two things
- Immutability
- Immutability pure function
so, immutability are which you can't change or modify it. That means you can't change the original data, you should always return a new copy.
This principle works in pure functions. some other rules of Pure function are ->
- have atleast one argument
- always return either a value or a function
High order function?
Function which take either another function as a argument or return a another function or both. for Ex:
- array.map(callback function)
- array.filter(callback function)
- array.reduce(callback function, currentvalue)
At the end, I would suggest you try to think declarative, try to do functional programming. Always return a new copy of argument in functions don't mutate the original one.
- Thanks guys
- Happy coding