Javascript Functional Programming Notes
Javascript Functional Programming Notes
First of all, I can say that functional programming is a programming paradigm, a coding style, or basically a mindset.
Some advantages are;
- safer
- easy to debug and maintain
- established community (that means there are so many experienced guys and threads to find solutions)
For a basic understanding, this is an example of writing code in a nonfunctional way and also a functional way.
Nonfunctional way
Functional way
Avoid side effects
Basically, the side effect is when a function relies on, or modifies, something outside its parameters to do something. For avoiding this you basically use just pure functions.
Pure functions basically are taking input and returning an output. The logic returning an output not doing something in basically.
Not pure function example
Pure function example
As you can see in the example just doing things is returning an output.
Use HOC (High Order Functions)
Very basically, functions can take inputs as a function or return a function as an output.
Don’t iterate
Basically, don’t use while, for and etc. Use high-order functions like map, filter, and reduce.
Avoid mutability
Basically, means changing objects in place. Instead of this use immutable data. (not changeable)
Mutation example
No mutation way
Copying elements instead of mutating can cause some efficiency problems. For a better understanding look up Persistent Data Structures. There are some libraries like Immutable.js, Mori and etc. for solving this problem.