DEV Community

Cover image for Understanding JavasScript OOPs
Arindam Majumder
Arindam Majumder

Posted on • Originally published at arindam1729.hashnode.dev

Understanding JavasScript OOPs

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?

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.

2. Prototype-based languages.

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

But Javascript is a Prototype-Based Programming Language!

💡 Note: Prototypes are the mechanism by which JavaScript objects inherit features from one another. ~ MDN Docs

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 class in JavaScript is actually a syntactic sugar 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.

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;
Enter fullscreen mode Exit fullscreen mode

Here you can see the code is too long!

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

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.
Enter fullscreen mode Exit fullscreen mode

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.

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

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,

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

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,

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
Enter fullscreen mode Exit fullscreen mode

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:

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
Enter fullscreen mode Exit fullscreen mode

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.

💡
Note: Using the new keyword with a regular function (not a constructor function) will not create a new instance and may lead to unexpected behaviour or errors. The new keyword is specifically used with constructor functions to create and initialize instances of objects.

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 and explore the various sponsorship options.

Connect with me on Twitter, LinkedIn, Youtube and GitHub.

Thank you for Reading :)

Top comments (1)

Collapse
 
rajaerobinson profile image
Rajae Robinson

Great post, very informative. For OOP I usually prefer using Typescript. I think OOP design patterns tend to be easier to implement in TS.