Understanding JavasScript OOPs
Tags: webdev, javascript, beginners, programming
Published: 2023-10-03 19:25:39

## Introduction:

Many Developers doubt whether JavaScript is a Functional Programming language or Object Oriented!

In reality, It's Both!

JavaScript is a prototype-based procedural language, which means it supports both functional and object-oriented programming.

In this article, we will learn and use Object-Oriented Programming (OOP) concepts in JavaScript.

## What is OOP?

![](https://miro.medium.com/v2/resize:fit:1250/1*BAWXQo-j9M9mKvk22a9Y6g.png)

> OOP is a programming paradigm that believes in grouping data (properties) and methods (actions) together inside a box. It demonstrates the pattern of real-world objects.

**There are two types of OOP languages:**

**1.** [Class-based languages](https://en.m.wikipedia.org/wiki/Class-based_programming).  
**2.** [Prototype-based languages](https://www.techopedia.com/definition/30040/prototype-based-programming).

So if you are coming from C++ or Java, you are familiar with Class-Based syntaxes.

But Javascript is a Prototype-Based Programming Language!

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><strong>Note:</strong> Prototypes are the mechanism by which JavaScript objects inherit features from one another. ~ MDN Docs</div>
</div>

### 4 Main Pillars of OOPs:

There are **four rules** or **main pillars** of Object-oriented programming language. This defines how the data and actions associated with the data; are organized using code.

1. Abstraction
    
2. Encapsulation
    
3. Polymorphism
    
4. Inheritance
    

## Does Javascript Have classes?

Yes and No!

What?

Confusing Right??

Let me explain this!

As I mentioned before, Javascript is a prototype-based Language; It doesn't have classes. We define the templates for objects using constructor functions or prototypes.

But Wait!

Javascript Does support the Class Keyword!

> **"The keyword <mark>class </mark> in JavaScript is actually a <mark>syntactic sugar </mark> over the prototype-based inheritance**, which is already present and supported in JavaScript."

Though It allows us to use the class keyword, It uses its Prototype-based mechanism under the hood. This is to help the Developers coming from class-based languages like C++, and Java.

## Object Literal:

It is a way to define an object using a simple and concise syntax. It allows us to create an object without using the traditional constructor syntax or the `Object.create()` method.

Let's Understand with some examples,

Before Object Literals, We used to create objects using `Object.create()`method Which was not much efficient.

```javascript
const personPrototype = {
  greet: function() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
  }
};

const person = Object.create(personPrototype);
person.name = 'Arindam';
person.age = 18;
person.isStudent = true;
```

Here you can see the code is too long!

Whereas, With Object literals, you can easily write the same program as:

```javascript
const person = {
  name: 'Arindam',
  age: 18,
  isStudent: true,
  greet() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
  }
};
person.greet(); // Output: Hello, my name is Arindam and I'm 18 years old.
```

## The 'this' Keyword:

Have you noticed that in the previous code, we have used `this.name` instead of `name` .

But why?

What's the significance of that "this" keyword?

Let's understand this with examples,

At first, we'll remove the `this` keyword from the code and see what happens.

```javascript
const person = {
  name: 'Arindam',
  age: 18,
  isStudent: true,
  greet() {
    console.log(`${name}`);
  }
};
person.greet(); // output:undefined
```

This program outputs undefined!

But why? We have already defined the name in the function!

This is because the greet function doesn't have any variable named `name` . when we tried to access the name property, javascript searched in the function scope(which is the greet function scope) and returned `undefined` .

To access the `name` property of the `person` object correctly within the `greet` method, you need to use the `this` keyword. The `this` keyword refers to the current object (in this case, the `person` object) that the method is being called on.

Here's the Bokish definition of `'this'` keyword:

> The `this` keyword in JavaScript refers to the context in which a function is executed.

## The 'new' Keyword:

> "The `new` keyword in JavaScript is used to create instances of objects from constructor functions. It plays a crucial role in object-oriented programming as it facilitates the process of creating objects with specific properties and behaviours."

Didn't understand? No worries!

Let's understand this with some examples,

```javascript
function User(username , age ){
    this.username = username;
    this.age = age;
    return this.name
}
const User1 = User(Arindam , 18);
console.log(User1);//output: Arindam
```

Here we have created a function named User which returns its name property. And created User1.

And the output same as our prediction.

Now let's create another user and see what happens,

```javascript
function User(username , age ){
    this.username = username;
    this.age = age;
    return this.name
}
const User1 = User(Arindam , 18);
const User2 = User(Diya, 17);
console.log(User1); //Output: Diya
```

Here we have created another User (Here it's User2) and printed the previous User (Here it's User1).

But wait! The output is not the same as before!

User2 Has overwritten the value of User1. As you can understand this is a serious issue. To solve this issue we use the `new` keyword.

Now, Let's do the same thing with `new` keyword and see what happens:

```javascript
function User(username , age ){
    this.username = username;
    this.age = age;
    return this.name
}
const User1 = new User(Arindam , 18);
const User2 = new User(Diya, 17);
console.log(User1); //Output: Arindam
```

Here the new keyword created instances of the constructor function (in this case it's User). So, we get two copies/instances of the function and there's no chance of data being overwritten.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Note: Using the <code>new</code> keyword with a regular function (not a constructor function) will not create a new instance and may lead to unexpected behaviour or errors. The <code>new</code> keyword is specifically used with constructor functions to create and initialize instances of objects.</div>
</div>

### Internal Working of new :

When you use the `new` keyword with a constructor function, the following steps take place:

1. A new empty object is created. This new object will become the instance of the constructor function.
    
2. The `this` keyword inside the constructor function is set to point to the newly created object. This allows the constructor function to refer to and set properties on the newly created instance.
    
3. The constructor function executes, and any properties or methods defined with `this` inside the constructor is added to the new instance.
    
4. If the constructor function does not explicitly return an object, the new instance created by `new` is returned as the result of the `new` expression. This allows you to store the created instance in a variable and use it later.
    

## Conclusion:

If you found this blog post helpful, please consider sharing it with others who might benefit. You can also follow me for more content on Javascript and other web development topics.

To sponsor my work, please visit: [Arindam's Sponsor Page](https://arindam1729.hashnode.dev/sponsor) and explore the various sponsorship options.

Connect with me on [Twitter](https://twitter.com/intent/follow?screen_name=Arindam_1729), [LinkedIn](https://www.linkedin.com/in/arindam2004/), [Youtube](https://www.youtube.com/channel/@Arindam_1729) and [GitHub](https://github.com/Arindam200).

Thank you for Reading :)

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1690696994936/47b58c3e-0efc-4490-8b51-0c6550d44eba.png)