UI Development

Functional Programming VS Object Orient Programming In Javascript

Hi Techies,

Are you ready to embark on the functional programming journey? You’ve come to the right place. Programming languages are a fundamental tool in a every programmer’s life and important to almost every activity related to programming. Today, we will looking into the key differences, head to head comparison and conclusions between Functional Programming and Object-Oriented Programming.

Objected-Oriented Programming (OOP) and Functional Programming (FP) are the two predominant patterns in JavaScript, mainly considered the two pillars of JavaScript. Both patterns have their own identity In JavaScript world.

First, we will start with the overview of Object-Oriented Programming in JavaScript In this blog i will cover major part of FP and will go deeper into the concept of Functional Programming which is something hard because nobody is talking about how to do it, because it can be a kind of subjective.

Object-Oriented programming is achieved in JavaScript through the use of prototypal inheritance. OOP use objects without classes, prototype delegation (objects linking to other objects).Object-Oriented programming works upon the idea of inheritance.Let see small example

Example: Create ‘Person’ object which has a name and a greeting in OOP way.

but the same approach for the functional programming is different from OOP approach as the stresses simple functions that provide one piece of functionality.

You must be thinking by seeing the above code why we have create the Person Object like this in function Programming. No need to worry let start the actually discussion and implementation of FP.

Simple<>Easy

We will learn about the benefits of learning functional programming languages along with examples of how tech giants have incorporated functional programming into their software development.

Introduction to Functional Programming:

What is a functional Programming in the first place and Why do we need to know it? The answer is pretty simple. The reality is that there isn’t any fixed definition of functional programming.

Functional Programming (often abbreviated as FP) is one of the type of program pattern that helps the process of building application by using of pure functions, avoiding shared state, mutable data, and side-effects.

Core Concepts of Functional Programming:

In order to understand the functional programming in practice then you have to understand the each and individual core concept in functional programming.

let start one by one:

Declarative vs Imperative :

Functional programming is a declarative pattern, meaning that the program logic is expressed without explicitly describing the flow control.imperative programs spend lines of code describing the specific steps used to achieve the desired results — the flow control:

Declarative programs remove the flow control process, and instead spend lines of code describing the data flow.

Example :

This imperative mapping takes an array of numbers and returns a new array with each number multiplied by 2:

This declarative mapping does the same thing, but remove the flow control away using the function utility, which allows you to more clearly express the flow of data:

Pure functions :

Pure function is a function which on giving 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.

Example : Pure Function Sample

This functional will always return the same output whenever argument passed to function. It is not depend on any outside scope variable Like if we call :

foo(9) ==> will return 9 always ,when we pass 9 as argument the output will return 9

foo(10) ==> will return 10 always ,when we pass 10 as argument the output will return 10

But if I want to modify the above function like below then still this same function will behave thePure function or not. Let check

n this function return x Is depend on outside scope variable x = 4; IF I call this function as

foo(9) ==> will return the 4;
foo(5) ==> will return the 4
but if this x variable is reassigned the value x to 6; like x = 6; then if I call the function like as

foo(9) ==> will return 6;

foo(5) ==> will return 6

Then if you notice this two calls First one foo(9) & foo(5) will return ‘4’ but after changing the value x it will return the different value. Then we can say that this function foo is not pure function because A function is depend on the variable X which is shared variable. So in functional programming we will not use such impure functions.

Function composition:

Function composition is the process of adding two or more functions in order to produce a new function or perform some computation. In order to understand the function composition let see some example.

Example:

Imagine Write a function checkSpam() that returns true if string contains ‘YYY’ or ‘XXX’, otherwise false. The function must be case-insensitive:

Now, imagine each of these operations had a corresponding composable function. This could be written as:

This looks even more harder to read and looks like a lot of nesting to me, We can remove the nesting with a function that will compose these functions for us automatically, meaning that it will take the output from one function and automatically patch it to the input of the next function until it spits out the final value.

In order to accomplish this, we’re using combine forms of common utilities like map() and filter` . Here are the implementations:

Note : Hardcore functional programmers define their entire application in terms of function compositions. you should be starting to get a sense of what functional programming is like, and how partial application & currying collaborate with function composition to help you write programs which are more readable.

 

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.

Example: Shared State Function

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.

How we can fix this ??

 

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. Immutable objects can’t be changed at all.Immutability is a central concept of functional programming because without it, the data flow in your program is lossy.

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:

The top level primitive properties of a frozen object can’t change, but any property which is also an object (including arrays, etc…) can still be mutated — so even frozen objects are not immutable unless you walk the whole object tree and freeze every object property.

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.

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

Side Effects:

A side effect is any application state change that is observable outside the called function other than its return value. Side effects are mostly avoided in functional programming, which makes the effects of a program much easier to understand, and much easier to test. Side effects has the following properties:

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.

Higher Order Functions:

JavaScript is first class functions, which allows us to use functions as data i.e as arguments — assign them to variables, pass them to other functions, return them from functions, etc. A higher order functionis any function which takes a function as an argument, returns a function, or both. Higher order functions are mainly used to:

  • remove individual actions, effects, or async flow control using callback functions, promises.
  • 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 vs OOP

Following is the Comparison Table Between Functional Programming vs OOP

Basic Difference

Functional Programming

OOP

1

Definition

Functional programming emphasises an usage of functions. Object-oriented programming based on a concept of objects.
2

Data

Functional programming uses immutable data. Object-oriented uses the mutable data.
3

Model

Functional programming does follow a declarative programming model. Object-oriented programming does follow an imperative programming model.
4

Execution

In Functional programming, the statements can be executed in any order. In OOPs, the statements should be executed in particular order.
5

Iteration

In Functional programming, recursion is used for iterative data. In OOPs, loops are used for iterative data.
6

Element

The basic elements of functional programming are Variables and Functions. The basic elements of object-oriented programming are objects and methods.
7

Use

The functional programming is used only when there are few things with more operations. Object-oriented programming is used when there are many things with few operations.

Conclusion

Functional Programming and Object-oriented programming both are different concepts of programming language. The aim of both Functional Programming vs OOP languages is to provide the bug-free code, which can be easily understandable, well-coded, managed and rapid development.

I am not writing this blog to tell you who will going to win the battle between FP vs OOP.

So Finally, I conclude, it is always up to the programmers or developers to choose the programming language pattern that makes their development productive and easy.

 

I hope you will like it. Keep Exploring & Keep Learning!!!

Sourabh Sen

About The Author