3.0 About functional programming - GiovanniKaaijk/functional-programming GitHub Wiki
What is functional programming?
Functional programming is a style, that values immutability, first-class functions, referential transparency, and pure functions. It avoid concepts of shared state, mutable data observed in Object Oriented Programming. Functional programming look very mathematical. Functional programming leads to modular code, you create small functions that you can reuse multiple times.
Immutability
Functions should not modify any data, for example: pop() or splice(). Instead: copy the data and modify the element you are looking for to modify, then return this new data.
First-class functions
First-class functions means you can pass these functions as variables and store them in variables.
Referential transparency
Functions should follow referential transparency, the outcome should always be the same. This is a good example:
function timesTwo (number){
return number * number
}
This is a bad example:
function calculate (number) {
return number * Math.random()
}
Pure functions
Pure functions operate independently from state outside of the function, so they shouldn’t rely on the global state, or variables outside of its own state.
Higher order functions
Higher order functions can do two things: they either take a function as one or more of its parameters, or they return a function. ES6 contains a lot of higher order functions, like: map
, reduce
, filter
, every
, reduce
, etc.
Functional programming vs Object oriented programming
In my opinion, functional programming and object oriented programming both have its own advantages. If you are creating an app that requires a lot of functions to be reused, I think functional programming is the way to go. Object oriented is a bit easier to do so I think this is more useful for small apps. Also the use of states can be useful in web apps. I think it is ultimately a personal opinion or preference.