What is functional programming

Functional programming means using functions as building blocks to construct a process. Unlike OOP, functional programming is not an imperative paradigm but a declarative one, meaning it describes what the code has to accomplish, but not how.


Languages such as Haskell have been completely written with functional programming in mind. Javascript also makes it possible to follow functional programming principles, however, it also supports OOP.


Below are some of the key concepts from functional programming

Pure functions

Pure functions are simple, reusable blocks of code written as functions, that don’t have any side effects, meaning the output of a function is defined by its input.


They should not modify anything outside of the function and should be stateless, meaning whenever the function runs, it should behave like it was its first time running. This also has more benefits like reducing the number of bugs that exist when there is a shared state between functions.


Example of an impure function that modifies a variable outside of itself.

Impure function example

Immutability

The main idea behind immutability is that when the data is created, it will never be mutated again. In functional programming, this is a key concept. It helps get rid of the rather complex bugs caused by mutating data over time. Libraries such as React and Redux, only provide a state which is not modifiable directly, instead, they make it possible to always create a new state instead.


ES6 array functions are an example of functions that don’t modify the data directly but instead always return a new one. One of them is the map function which can be seen in the example below.


ES6 map function example

Conclusion

Functional programming can be very useful whether you are building frontend web applications or any other type of app. So if you haven’t already, I hope you give it a try and check for yourself if it's easier writing functional code.



Are you interested in reading more about Frontend in general? Then make sure you follow us on Twitter to get the latest updates.