All posts
Published in javascript

Javascript Functional Programming Notes

Profile image of Atakan Demircioğlu
By Atakan Demircioğlu
Fullstack Developer

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

Javascript Functional Programming Notes image 1

Functional way

Javascript Functional Programming Notes image 2

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

Javascript Functional Programming Notes image 3

Pure function example

Javascript Functional Programming Notes image 4

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

Javascript Functional Programming Notes image 5

No mutation way

Javascript Functional Programming Notes image 6

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.