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.


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:
const doubleMap = numbers => {
  const doubled = [];
  for (let i = 0; i < numbers.length; i++) {
    doubled.push(numbers[i] * 2);
  return doubled;
console.log(doubleMap([2, 3, 4])); // [4, 6, 8]

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:

const doubleMap = numbers => numbers.map(n => n * 2);
console.log(doubleMap([2, 3, 4]));
// [4,6,8]

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

function foo(x){
return x;

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

var x = 4; 
function foo(){

return x;

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.


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

var stringArray = ['yyy','innocent rabbit','free','xxx'];
const checkSpam(stringArray) {
let lowerString = stringArray.map(str => str.toLowerCase()).filter((str) => {
     return str.includes('yyy') || str.includes('xxx')
 return  lowerString.length > 0 ? true : false;

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

let stringArray = ['yyy','innocent rabbit','free','xxx'];
const checkSpam = inputArray => checkReturnArrayLength(
        ‘string matching’

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:

const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const curry = fn => (...args) => fn.bind(null, ...args);
const map = curry((fn, arr) => arr.map(fn));
const filter = curry((fn, arr) => arr.filter(fn));

const toLowerCase = str => str.toLowerCase();
const checkReturnArrayLength = arr => arr.length > 0 ? true : false;

const checkSpam = compose(
  filter(string matching)

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

const x = {
  val: 2

const x1 = () => x.val += 1;
const x2 = () => x.val *= 2;

console.log(x.val); // 6

// This example is exactly equivalent to the above, except...
const y = {
  val: 2

const y1 = () => y.val += 1;
const y2 = () => y.val *= 2;

// ...the order of the function calls is reversed...

// ... which changes the resulting value:
console.log(y.val); // 5

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 ??

const x = {
  val: 2

const x1 = x => Object.assign({}, x, { val: x.val + 1});
const x2 = x => Object.assign({}, x, { val: x.val * 2});
console.log(x1(x2(x)).val); // 5

const y = {
  val: 2

// Since there are no dependencies on outside variables,
// we don't need different functions to operate on different
// variables.

// this space intentionally left blank

// Because the functions don't mutate, you can call these
// functions as many times as you want, in any order, 
// without changing the result of other function calls.

console.log(x1(x2(y)).val); // 5.


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:

const a = Object.freeze({
  foo: 'Hello',
  bar: 'world',
  baz: '!'

a.foo = 'Goodbye';
// Error: Cannot assign to read only property 'foo' of object Object

But frozen objects are only superficially immutable. For example, the following object is mutable:

const a = Object.freeze({
  foo: { greeting: 'Hello' },
  bar: 'world',
  baz: '!'

a.foo.greeting = 'Goodbye';

console.log(`${ a.foo.greeting }, ${ a.bar }${a.baz}`);

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




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


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


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


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


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


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


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.


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