Getting a hang of Object Oriented Programming in JavaScript

That one programming concept that consistently kept me struggling for long happens to be Object Oriented Programming. I am also kind of sure that I am not alone in this struggle. My biggest concerns about object oriented programming have been the following:

  • Why do it at all ?
  • Why are objects call objects?
  • What makes it better than the usual procedural algorithms?
Object Oriented Programming JavaScript
Object Oriented Programming JavaScript

I finally believe that I am getting a hang of it. Thanks to a great Udemy course on JavaScript by Mosh Hamedani. Do note I am not paid by Mosh or Udemy for this endorsement. This endorsement is my way of thanking Mosh for showing me the light! Ok … pardon the theatrics.

I also feel the need to help out everyone else who have been struggling with the concept (just like me).

So why do Object Oriented Programming?

Simple answer: It’s smarter.

Just like functions , the correct usage of objects make your code more logical and efficient. Think about it. If you have to reuse a particular block of code over & over again – it makes sense to wrap it up in a function & call the function as & when needed.

Similarly if a block of variables & functions are closely linked together – it makes sense to group them together as an object.

Why do we need to group stuff together into objects?

Let’s consider a simple example at this point. Imagine that we are running a school & for every student we need to store the following information:

  • Name
  • Age
  • Height (in meters)
  • Weight (in Kg)
  • Body Mass Index (BMI) = Weight/height^2

Let’s consider a scenario whereby there are a 10 students. How many variables would it need to store all the info ? Without Object oriented programming we would need 50 (10 x 5) odd variables.

// Student 1 data
let Name1 = "A";
let Age1 = 7;
let Height1 = 1.20 ;
let Weight1 = 25;
let BMI1= Weight1/Math.pow(Height1,2)
         

// Student 2 data
let Name2 = "B";
let Age2 = 6;
let Height2 = 1.15;
let Weight2 = 26;
let BMI2= Weight2/Math.pow(Height2,2)
// and so on ...

Isn’t it long & boring ? Also it’s prone to a lot of possible data errors in future.

Object oriented programming , brings that down to 10 right-away!

The concept actually isn’t that convoluted. It starts with imagining each student as an entity. Name, age, height , weight and BMI are parts of this entity. In computer programming such entities are called objects. The parts assigned to these objects are the properties & methods.

Here’s how we would make the below code Object oriented:

let Student = function(name,age,height,weight){
                     this.name = name;
                     this.age = age;
                     this.height = height;
                     this.weight = weight;
                     this.bmi = function () {
                                   return weight/Math.pow(height,2)
                     }
                     }
 let Student1 = new Student("A",7,1.20,25)
 let Student2 = new Student("B",6,1.15,26)    

// ... and so on                                            

So what did we do? Instead of toiling in a mess of variables, we defined a “Student” and included name, age, height & weight as a part of that definition. ( I must admit that it feels a bit divine)

Now we just reuse the definition (with actual data-points) to store that data for each student.

The function that we used to create the definition , is called Object Constructor. By definition, A constructor is a function that initializes an object.  In this case, we initialized “Student” to understand that the first argument would be name, the second one would be age, the third one would be height and so on…

The “this” keyword, helps with the mapping. In the constructor, when we mention this.name = name, we imply that the value “name” is assigned to the key “name”. The key “name” was passed as an argument to the constructor function.

The definition infact is called “Class“. The other way of writing the above code would be:

Class Student { 
       constructor(name,age,height,weight){
                     this.name = name;
                     this.age = age;
                     this.height = height;
                     this.weight = weight;
                     this.bmi = function () {
                                   return weight/Math.pow(height,2)
                     }
                     }
                }

The variables Student1 , Student2 etc. are the Objects. Objects thus are instances of the class. We use the “new” keyword to map the objects to the class. In this case , Student1 = new Student(“A”, 7, 1.20, 25), implies that Student 1 is an instance of class Student with values “A” , 7 , 1.20 & 25.

The constants like Name, age, height & weight are called properties. On the other hand BMI, being a function, is called a “method”. When we define a class , we can add both properties and methods.

In a real world equivalent, consider yourself as the administrator of the above school. You have 2 choices:

  • Choice 1: Store individual student datapoints (e.g. “A”, “B”, 1.2, 22 etc.) in separate sheets of paper.
  • Choice 2: Store all the datapoints related to a particular student in a single sheet of paper

What would you Choose? It seems really obvious. In the real world possibly we are subconsciously all object oriented!

Before we conclude, let’s check the following:

  • How is data stored in an object?
  • How to retrieve data from an object?

How is data stored in an Object?

A simple console check (e.g. console.log(Student1) ) tells us how the data is stored in an object. Here’s an example:

Student1 = {
    name = 'A',
    age = 7,
    height = 1.2,
    weight = 25,
    BMI = [Function]
}

It’s a straightforward collection of variables & functions separated by commas.

How to retrieve data from an Object?

The properties & methods can be easily retrieved for a particular object. The syntax however is slightly different.

In case of a property, we need to use the following syntax:

Object.property

Example: Student1.name

In case of methods, we need a slightly different syntax (just like calling a variable vs. calling a function) :

Object.method(arg1, arg2 …)

Example: Student1.BMI()

If you are interested , you may check out how I used object oriented programming to simplify an EMI calculator program.

Inheritance in JavaScripts

Inheritance is a critical concept in object oriented programming irrespective of programming language. Classical inheritance allows methods from base class to get copied into derived class. In JavaScript, inheritance is supported by using prototype object. To understand better let’s check the following example.

function Performance (Name ,grade)
{
    Student.call(this, Name);
    this.Grade = grade
}

Performance.prototype = new Student();
Performance.prototype.constructor = Performance;

In the above case, we created a new Class called Performance. This Class stores the Name and Grade of a student. Instead of defining the Name again, we use inheritance to inherit the same from the Class student. This is done by the Student.call object. We then set the Performance.prototype to a newly created Student object using the “new” keyword. Following which , the line Performance.prototype.constructor = Performance; assigns the Performance Constructor to the Performance class.

FAQs : Object Oriented Programming in JavaScripts

Does JavaScript have oops concept?

JavaScript supports Object Oriented Programming (OOP) and the same can be used well to reorganize your code and make it scalable.

What is the purpose of object oriented programming?

The purpose of OOP is to organize a program’s structure so that one can build programs using these abstract models called “objects” that encapsulate data and behavior into one unit.

Summary
Object Oriented Programming in JavaScripts | Tutorial with code examples
Article Name
Object Oriented Programming in JavaScripts | Tutorial with code examples
Description
If you are struggling to understand Object Oriented programming, to read on. The article explores the purpose and basics of OOP using JavaScript.
Author
Publisher Name
Digital Marketing Chef
Publisher Logo

5 thoughts on “Getting a hang of Object Oriented Programming in JavaScript”

Leave a Reply

Your email address will not be published. Required fields are marked *