JavaScript – Core Concepts of Functional Programming

In this article, we will learn about the functional programming core concepts in JavaScript which helps to improve your functional code tends to be more concise, more predictable, and easier to test.

Functional programming has become a really hot topic in the JavaScript World.
So, “What is functional programming ? “The Answer is :

Functional Programming is :
  • The process of building software by composing pure functions, avoiding shared state, mutable data, and side-effects
  • Declarative rather than imperative, and application state flows through pure functions.
  • A programming paradigm, meaning that it is a way of thinking about software construction based on some fundamental, defining principles.

In Contrast with object oriented programming, where application state is usually shared and colocated with methods in objects.

Other examples of programming paradigms include object oriented programming and procedural programming.

We can say that in functional programming, functional code tends to be more concise, more predictable, and easier to test than imperative or object oriented code.

After that, Second question is in our mind that :

“Why is it most important in the JavaScript World ?”

To understand the meaning and importance of the functional programming, we need to understand the below core concepts:

  • Pure functions
  • Function composition
  • Avoid shared state
  • Avoid mutating state
  • Avoid side effects
  • Reusability through Higher Order Functions
  • Declarative vs Imperative

1. Pure function :

A pure function is a function which :
  • Given the same inputs, always returns the same output, and 
  • Has no side-effects
Pure functions have lots of properties that are important in functional programming, including referential transparency (You can replace a function call with its resulting value without changing the meaning of the program). 

2. Functional Composition :

Functional composition is the process of combining two or more functions in order to produce a new function or perform some computation. For example, the composition f.g (the dot means “composed with”) is equivalent to f(g(x)) in JavaScript. Understanding function composition is an important step towards understanding how software is constructed using  the functional programming.

3. Avoid Shared State :

Shared state is any variable, object, or memory space that exists in a shared scope, or as the property of an object being passed between scopes. A shared scope can include global scope or closure scopes.
Often, in object oriented programming, objects are shared between scopes by adding properties to other objects. 
For example, a computer game might have a master game object, with characters and game items stored as properties owned by that objects. Functional programming avoids shared state  instead relying on immutable data structures and pure calculations to derive  new data from existing data.
Here question comes in our mind, that Why avoid the shared state?
So there is two common problems with shared state :
  • The first problem with shared state is that in order to understand the effects of a function, you have to know the entire history of every shared variable that the function uses or affects.
  • Another common problem associated with shared state is that changing the order in which functions are called can cause a cascade of failures because functions which act on shared state are timing dependent.
When you avoid shared state, the timing and order of function calls don’t change the result of calling the function. With pure functions, given the same input, you’ll always get the same output. This makes function calls completely independent of other function calls, which can radically simplify changes and refactoring. A change in one function, or the timing of a function call won’t ripple out and break other parts of the program.

4. Avoid mutating state :
An immutable object is an object that can’t be modified after it’s created. Conversely, a mutable object is any object which can be modified after it’s created.
Immutability is a central concept of functional programming because without it, the data flow in your program is lossy. State history is abandoned, and strange bugs can creep into your software.

So here question comes in our mind, Why we talk about immutability or an immutable object ? but here topic heading is avoid mutating state.


So, to understand avoid mutating state concept, we need to first understand An immutable object or Immutability concept.
In JavaScript, it’s important not to confuse const, with immutability. const creates a variable name binding which can’t be reassigned after creation. const does not create immutable objects. You can’t change the object that the binding refers to, but you can still change the properties of the object, which means that bindings created with const are mutable, not immutable.Immutable objects can’t be changed at all. You can make a value truly immutable by deep freezing the object. JavaScript has a method that freezes an object one-level deep.But frozen objects are only superficially immutable.

 Then one more question comes in our mind, How to implement deep frozen for object and which mechanism or data structure is used?
 
In many functional programming languages, there are special immutable data structures called trie data structures (pronounced “tree”) which are effectively deep frozen — meaning that no property can change, regardless of the level of the property in the object hierarchy.
Tries use structural sharing to share reference memory locations for all the parts of the object which are unchanged after an object has been copied by an operator, which uses less memory, and enables significant performance improvements for some kinds of operations.
For example, you can use identity comparisons at the root of an object tree for comparisons. If the identity is the same, you don’t have to walk the whole tree checking for differences.

There are several libraries in JavaScript which take advantage of tries, including Immutable.js and more.

5. Avoid side effects :

A  side effect is any application state change that is observable outside the called function other than its return value. 

Side effects include : 
  • Modifying any external variable or object property (e.g., a global variable, or a variable in the parent function scope chain)
  • Logging to the console
  • Writing to the screen
  • Writing to a file
  • Writing to the network
  • Triggering any external process
  • Calling any other functions with side-effects
Side effects are mostly avoided in functional programming, which makes the effects of a program much easier to understand, and much easier to test. Haskell and other functional languages frequently isolate and encapsulate side effects from pure functions using  monads.

If you keep your side effects separate from the rest of your program logic, your software will be much easier to extend, refactor, debug, test, and maintain.
This is the reason that most front-end frameworks encourage users to manage state and component rendering in separate, loosely coupled modules.

6. Reusability through Higher Order Functions :

higher order function is any function which takes a function as an argument, returns a function, or both. Higher order functions are often used to:
  • Abstract or isolate actions, effects, or async flow control using callback functions, promises, monads, etc…
  • Create utilities which can act on a wide variety of data types
  • Partially apply a function to its arguments or create a curried function for the purpose of reuse or function composition
  • Take a list of functions and return some composition of those input functions
Functional programming tends to reuse a common set of functional utilities to process data. JavaScript has first class functions, which allows us to treat functions as data — assign them to variables, pass them to other functions, return them from functions, etc…

7. Declarative vs Imperative:

Functional programming is a declarative paradigm, meaning that the program logic is expressed without explicitly describing the flow control.
The two difference between Declarative and Imperative programs are :
  • Imperative programs spend lines of code describing the specific steps used to achieve the desired results — the flow control: How to do things. Where as Declarative programs abstract the flow control process, and instead spend lines of code describing the data flow: What to do. The how gets abstracted away.
  • Imperative code frequently utilizes statements. A statement is a piece of code which performs some action. Examples of commonly used statements include forifswitchthrow, etc… where as Declarative code relies more on expressions. An expression is a piece of code which evaluates to some value. Expressions are usually some combination of function calls, values, and operators which are evaluated to produce the resulting value. 

Conclusion
 
In this article, We understood the functional programming core concepts in JavaScript. In Summary, Functional Programming favors :
    • Pure functions instead of shared state & side effects
    • Immutability over mutable data
    • Function composition over imperative flow control
    • Lots of generic, reusable utilities that use higher order functions to act on many data types instead of methods that only operate on their colocated data
    • Declarative rather than imperative code (what to do, rather than how to do it)
    • Expressions over statements
    • Containers & higher order functions over ad-hoc polymorphism
Thanks for reading ! I hope you enjoyed and learned about the functional programming core concepts in JavaScript. Reading is one thing, but the only way to master it is to do it yourself.
If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

 

Thanks again Reading. HAPPY READING!!😊😊😊

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s