Loading...

Object-Oriented Programming in JavaScript- Guide with Examples

Object-Oriented Programming in JavaScript- Guide with Examples

JavaScript is the most popular and hyped language in the market right now. According to StackOverflow’s 2020 report, JavaScript is the most popular and in-demand language in the world. The reason is obvious, if you want to start your web development career then it is almost impossible without object-oriented programming in JavaScript.

JavaScript is used in both the front-end and back-end of a website, there are a lot of other languages in the backend but JavaScript without the front end is almost impossible. So, what makes JavaScript so popular? 

One of the reasons is this language has that JS is an Object-Oriented programming language. So, why not find out what is it? And how you can implement Object Oriented Programming in your code? 

What is Object Oriented Programming in JavaScript

So, the one thing that many programmers will describe as an OOP ( Object-Oriented Language) is the class system. We will talk about it later in this article, but in JavaScript, the concept of OOP is not as similar as in other languages. 

One of the reasons is that JavaScript does not use the traditional class-based system; instead, it uses objects, which we will discuss further later. JavaScript is more like a prototype OOP language, where it will use some concepts but not properly. 

Types of OOP languages 

Object-oriented languages are a vast concept where you get to do some powerful work without writing too much or repeating the same code again and again. Here we will discuss two types of OOP. 

Class-based Language 

If you want to learn about true OOP, this is the class-based OOP language to use. Here, we get to use something called a class, where all the properties for one object will be there. Further down the line, there will be some code examples that may clarify your concept of classes. 

Some, well-known OOP class-based languages are C++, Java, Python, etc. 

Prototype Based Programming

In this case, we use one concept via inheritance with some objects, which is referred to as a “prototype.” You can clone that object or extend it, basically in the way that suits you best. JavaScript is the most well-known language that uses this concept.

Features of OOP in JS

Before we get into the code, we need to look at some of the concepts that you should know, The 4 basics of Object-oriented programming are: 

  • Objects 
  • Classes
  • Encapsulation 
  • Inheritance

Objects

Objects are the thing that makes OOP such a powerful concept in the programming world. Inside an object, you have properties and methods. One of the most common ways to explain Objects is the concept of animals. Consider two animals, dogs and cats, Both of these animals have legs, is a pet. If you are to differentiate between a cat and a dog then you might say a cat mews and a dog barks. 

These characteristics of those animal objects are the properties and what they do is the methods. Ok enough of these real-world examples, what are methods in JavaScript? Very often, you have to use functions inside your objects, these functions inside that class are the method. 

You can sometimes use another object inside one object, which is also possible in the JavaScript language. 

Creative Objects in JavaScript

Objects are fascinating; you’ll be amazed at how many different ways you can define a function and use it in various programs. 

Method 1

So, let us write a program that will describe a person with relevant information. 

let person = { first_name:'Shafkat', last_name: 'Sakir', welcome: function(){ return (`Welcome ${person.first_name} ${person.last_name}`) }, //object within object contactInfo : { mobile:'1234', landline:'56789' } } console.log(person.welcome()); console.log(person.contactInfo.landline);
Code language: JavaScript (javascript)

How do you define a person? Look at the code we have done here: inside an object, there is the first name, last name, and a function or method that will display the output of that person’s full name. We have also added another object that contains that person’s contact information. This is enough information for someone to know about an unknown person. 

And notice something else? This code has a fixed value based on the name and contact information. Let us rewrite that code so we can reuse it for different people. 

Method 2

Let us write a simpler code this time, one that displays the output of a person’s full name. Instead of doing it for just one person, we will do it for multiple people using the same code. 

function person(first_name,last_name){ this.first_name = first_name; this.last_name = last_name; } let person1 = new person('Shafkat','Sakir'); let person2 = new person('Arshiya','Bithi'); // You can go on as much as you like console.log(person1.first_name); console.log(`${person2.first_name} ${person2.last_name}`);
Code language: JavaScript (javascript)

By following this code, you can output the name of as many people as you want; you don’t have to write the same object again and again for each person. That is one of the many reasons why objects are so great. This way of using the object is known as the “object constructor”.

And notice another thing in this code, instead of using your typical objects, we have created a function and used it to create one object. 

Method 3

Now, let’s create an object unfortunately we will need another property in that object but we don’t want to change the first object either. Here, the object.create() method will help us as it will create another object for us based on the previous object we wrote. Now, you don’t have to write another object just to use your previous one.   

const coder = { isStudying : false, Intro : function(){ console.log(`My name is ${this.name}. Am I studying?: ${this.isStudying}.`) } } const shafkat = Object.create(coder); shafkat.name = 'Shafkat'; shafkat.isStudying = true; shafkat.Intro();
Code language: JavaScript (javascript)

Check out this code, here in our first code there was no name properly in that object but look what we did later in that code, we have assigned that name property inside our newly constructed object. 

Classes

Whenever you ask someone about Object-oriented programming language, the shortest answer you might get is that it is an OOP is something with classes. Why is that? Why everyone is so fond of classes in any sort of OOP language? 

Classes are, in short, a template that your code will follow to avoid the repetition of certain codes. What about classes in JavaScript? JavaScript does not have classes; instead, it uses objects, which is an interesting fact.

Is JavaScript Object Oriented?

The short answer is yes, but why is JavaScript object-oriented? JavaScript lacks the main quality of an object-oriented language: classes. You can say that JavaScript also has classes; now, what are we talking about? Yes, JavaScript has something called classes, but look at the structure below:

class Rectangle { constructor(height, width) { this.height = height; this.width = width; } }
Code language: JavaScript (javascript)

This code is taken from official JavaScript Documentation.

Found something similar? Yes, the classes in JavaScript are nothing but objects acting as a “prototype class”. So, is JavaScript object-oriented? Yes, but not like your regular programming language; it is more like a prototype of an object-oriented language.

Encapsulation

I hope all of you are reading this and are familiar with capsules. A cylindrically shaped medicine with a lot of smaller particles The concept of encapsulation almost works in the same way. This is a concept where you put all the wrapping properties and functions under the same class or capsule. 

Encapsulation in JavaScript

So, let us do a similar program as we did in the previous example. 

class person{ constructor(name,id){ this.name = name; this.id = id; } Address(address){ this.address = address; } getDetails(){ console.log(`I am ${this.name},Address is: ${this.address}`); } } let person1 = new person('Shafkat',23); person1.Address('Dhaka'); person1.getDetails();
Code language: JavaScript (javascript)

Look at how we’re using this code without worrying about the implementation. Sometimes, programmers use encapsulation just to hide data, so we try to hide the background data. Unlike other OOP languages, JavaScript does not provide the ability to restrict the scope of an object within classes. 

Inheritance

The final concept you should know about OOP is inheritance, it’s the same as inheriting properties from previous generations. The next generation inherits the name and properties from the previous generation, the same thing can be done with a JavaScript object. 

Inheritance in JavaScript

One object can inherit properties from another object, so why not check out an example for a better understanding: 

class student extends person{ constructor(name,id){ //super keyword for calling the above class constructor super(name); this.id = id; } toString(){ return (`${super.toString()}, ID: ${this.id}`); } } let student1 = new student('Shafkat',23); console.log(student1.toString());
Code language: JavaScript (javascript)

The first object we wrote is describing a person, another one is describing a student. A student can be a person too, so instead of writing the same code for the student as we did in person, why not just use the properties of a person inside the student? This will make our code cleaner and easy to write and other coders will also understand it easier.

Conclusion 

If you are planning to enter the world of web development then you must know about JavaScript. Without the OOP part of this language, it will be impossible for you to be better at this language.  

Frequently Asked Question

What are the object-oriented concepts in JavaScript?

JavaScript does not follow the traditional class-based system, rather they use objects that act the same as the class, this is called prototype-based OOP.

What are the objects of JavaScript, explain with examples.

Objects are a piece of code in JavaScript containing methods and properties that you can repeatedly use to prevent bloating. The structure goes as below:

const objects = { properties : 'keys' method: function(){ } }
Code language: JavaScript (javascript)

What are the 4 basics of OOP?

  • Objects
  • Classes
  • Encapsulation
  • Inheritance

How long does it take to learn OOP JavaScript?

It should not take more than a week to understand the concept of OOP JavaScript, but it could take months to master when and how to use OOP effectively.

Why JavaScript is object-oriented?

Although JavaScript does not follow the traditional class-based system it does have something called an object that follows the prototype-based OOP system, that is what makes it OOP.

Sharing is caring

Did you like what S.M. SHAFAKATUL ISLAM wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far