An introduction to Object-Oriented Programming in JavaScript

Mar 05, 2019

This article focus on the parts of OOP that are only relevant for JavaScript and not OOP in general. That's why polymorphism is skipped because it fits better with a static-typed language.

The Object-Oriented Paradigm

Ok...Lets first understand what OOP is ? OOP is a way to order your codes in Javascript to make it more orderly. When it comes to writing codes for a program, the program can become quite large and thats where OOP comes into play.                                                       From the OOP perspective, an application is a collection of “objects” that communicate with each other.

Object as Centerpiece  

A simple example will help you see how JavaScript implements the fundamental principles of OOP. We will consider a shopping use case in which you put products into basket and then calculate the total price you must pay.

If you take your JavaScript knowledge and code the use case without OOP, it would look like this:

const water = {name: 'Water', price: 0.25};
const basket = [];
const total = basket
  .map(product => product.price)
  .reduce((a, b) => a + b, 0);
console.log('one has to pay in total: ' + total); ```

Here we have two kinds of objects — the basket object and the product objects.                     The OOP version of the shopping use case could be written like:

const water = new Product('water', .25)
const basket = new Basket();
basket.addProduct(2, bread);
basket.addProduct(3, water);
basket.printShoppingInfo();  ```

In the first line, we create a new object by using 'new' keyword and stores it to the variable 'bread' . We repeat that for variable 'water' and 'basket'.

The difference between the two codes is obvious. The OOP version almost reads like real English sentences and you can easily tell what’s going on.

Lesson : Using objects helps our program look more readable and understandable.

In this blog we have learned just about "Objects". The further OOPs concept will be covered in next blogs so just stay tuned..

I hope this blog helps understanding 'Objects' of OOP in javascript.                                         Thankyou all for reading.

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.