Functional Programming in JavaScript



There are different "paradigms" (just a fancy word which means "ways of programming"!) in JS programming like Object Oriented, Functional, Imperative etc

Object Oriented involves all the OOPS concepts as we all know like Inheritance, Abstraction, Encapsulation, Polymorphism

Imperative programming involves coding in an imperative way, like first do this, then do that etc



Functional Programming

Everything is expressed in the program in terms of “functions”. This function takes an input and returns the transformed data as output

  •   Avoid side effects in functions, Use PURE functions: Any function that computes its output purely from the inputs it receives as arguments (should not modify other global data, change any other variable). Printing something to the console is also not “returning” an output.

Basically, the function has to read the input, take that, and only that to compute an output.


Functional programming means thinking of functions as purely as possible

  •  Use Higher Order Functions: Functions can be inputs/outputs to other functions.


  • Do not iterate (for loops). Instead use map/filter/reduce: Pass on variables/functions to map/reduce/filters and also get back functions as output

  • Data is immutable: In functional programming, we should not modify/change any variable’s value. Instead, we create copy and use this modified variable
Mutated: Bad

Not Mutated: Good!

However, with this style of programming we end up with lot of copies of “almost” same data, and unintended change to data might occur which might introduce bugs. So, libraries like immutable.js, Mori etc is used

Overall idea of what it does is:

Original Data-structure:

“size”

“color”

“length”

“type”


Array is represented as a bunch of tree nodes. A new node is created containing “category”. Other nodes are not repeated but re-used. The tree now points to this new node instead of previous “type” leaf node


This design is known as “Persistent Data Structure”. This is “structural sharing”, where parts of old versions are shared to the new version so we now have much more efficient code

Comments

Popular posts from this blog

Inside the JavaScript Memory Box: Visualizing Variables, References, and Copies

React & State Management: All Concepts

React: Communication between components