Functional Programming vs Object-Oriented Programming in JavaScript

By Sundeep Charan Ramkumar

Sundeep Charan Ramkumar
UpSkillie
Published in
5 min readJan 3, 2020

--

Table Of Contents

  1. Introduction
  2. What Is Functional programming?
  3. What Is Object-Oriented Programming?
  4. Analyzing key topics
  5. Conclusion
  6. Resources

Introduction

In this article, we are going to view two main design paradigms which Javascript developers use, and have a broad range of thought on where each paradigm might be useful and be advantageous.

What is Functional Programming?

Functional Programming or in other words, Pure programming in Javascript is a design pattern where the developer designs the code in such a way, there exists neither any side effects nor local use of scopes. Let’s view it with a code example.

If you could see the first code snippets batch, they were inducing side effects, which in other words triggered uncertain code actions and changed the original dataset. The following snippets batch, the side-effects were not created inside that function but instead returned the value, which is then up to the user to handle the result. We duplicate the object’s data so that there exists no manipulation on the original data. This is the base of functional programming.

What Is Object-Oriented Programming?

Now that we had gained a basic understanding of what Functional Programming is, let’s gain a small view about Object-Oriented Programming.

  • For the next 5 seconds, look around yourselves and pick any non-living thing. It may be a clock, a headphone, a PS4 controller whatever.
  • Now analyze its physical shape and size. Say, for example, the clock is round in shape and has a minute hand, second hand, hour hand. Similarly, a PlayStation controller is trapezoidal with various buttons.
  • The final step to conclude your analysis is to have a basic idea of what work do they do as descriptive as possible. A clock tells it’s time by moving its second’s hand 60 times which, as a result, moves the minute hand by 1 step. 60 steps of minute hand results in incrementing the hour hand by 1 step.

This complete analysis of what we just went through is called Object-Oriented Design. It profoundly inspires real-world entities and then models around them. Although it takes some time to wrap our heads around, designing in this method concerning real-world models make sense most of the time. Let’s take an example

Let’s take a step back and review what we had done in the above snippet.

  • ES6 Classes in Javascript do not reflect real classes like in Java or C++. They are just functions. Explaining about this topic would take an entire article. Hence that is left aside, but right now understand that in Javascript class keyword is just syntactic sugar for functions.
  • We have this constructor method inside the class to create new instances (new entities). Class is just a blueprint of how each of its children is going to behave. We pass in the object’s arguments via the new keyword, in this case, bricks, cement, and wood.
  • Each instance/object of that class has access to the methods inside the class. For demonstration purposes, We are going to view just one method, but a class can have countless methods inside. Here we have this method called buildHouse(), where we convert raw materials into a finished product.

Analyzing key topics of both paradigms

The basics of both Functional Programming, as well as Object-Oriented Programming, have been discovered in the above sections. Let us analyze the unique feature of these design patterns.

  1. Functional Programming
  • Higher-order function
  • https://gist.github.com/076ffc8419497a6defcf5a3e9092026d
  • Here the base concept is to have a base function that returns another function that has the resultant value. This is called as Higher-Order Function.
  • Composition This technique is very much similar to how we use our mathematical functions. Consider having a process of baking a cake. Normally we would need to add the ingredients, put into a mold and place it in the oven. If we convert the process in terms of mathematical jargon, we would perceive it as PlaceOven(PutIntoMould(AddIngredients(‘egg’, ‘chocolate’, ‘icing-sugar’), ‘square’), ‘350deg’). It is similar to H(G(F(x))).
  • https://gist.github.com/e5736cc4402ae73ab48a33d92bdbf67e
  • The key takeaway from the above snippet is composition calls from the left to right. Just like any nested differentiation or integration in mathematics.
  1. Object-Oriented Programming.
  • Static Methods Static methods work similarly to higher-order functions in Functional Programming. In static methods, a predefined value can be used with the class itself, because static methods are not bound to the objects but to the class itself.
  • https://gist.github.com/c37ebaa91cec375902a30b710df44714
  • The significant advantage of static methods is that they have a single copy and not a dynamic memory allocation. This method would pave the way to a single source of truth, or in other words, purity of the value.
  • Inheritance Let’s suppose a gardener sells ornamental plants as a side hustle, and we as developers have the power to build him an application for monitoring the revenue as well as the plants which he had sold. As time goes by, he buys many sorts of plants. It doesn’t seem very easy to rewrite the description of each plant, which at the end of the day was the same for all. Inheritance saves the day for this problem. Let's look over with an example
  • https://gist.github.com/8265baeeef731e3cf5e6913ba4eadc42
  • Let’s discuss what happened at the above snippet. We have a regular Plant class, that has a name and color properties. It also has a grow function which increases its height by 1cm. As you can see, every plant shares these properties. So we designated this class as the parent. Aloevera class is a derived/child class which has some special attributes like the size but also inherits its parent properties as well. The super method allows instantiating the parent constructor. In javascript, to use this keyword, we mandatorily have to assign the super method.
  1. We could also write the aloe vera and plant relationship in a functional programming way by merging one more object into a large object. The base rule of composition is to join a significant method from smaller chunks of code.
  2. https://gist.github.com/7ffc0d893a672851dc58745383e43187
  3. We can extend the functionality to want, however, but I would like to give the bare bones of it.

Conclusion:

The hype between Composition vs Inheritance and Functional Programming and Object-Oriented Programming is real, but people would go with what others say, and, I would say that is a bad idea. Sure being updated and going with the trend is fine, but at the same time knowing what is required currently for our design architecture is highly important as well. To be honest, there isn’t a solid goto solution as both shine in different aspects. However, there exists a pattern behind them. If your design pattern requires a hierarchical pattern with the need to create multiple counterparts from an object with dynamic properties like say for example game design, then OOP IS THE WAY TO GO. However, if purity is a concern, and you want to minimize side effects, then Functional Programming might be of an idea. I will post the resources for allowing further research.

Resources

  1. Functional Programming vs OOP By educba: https://www.educba.com/functional-programming-vs-oop/
  2. Fireship’s awesome video on FP vs OOP in TypeScript (Similar to TypeScript) https://www.youtube.com/watch?v=fsVL_xrYO0w
  3. Packt Publications on FP vs OOP https://hub.packtpub.com/what-difference-between-functional-and-object-oriented-programming/

--

--

Sundeep Charan Ramkumar
UpSkillie

A MERN Stack developer who builds single page/Ecommerce applications for a living