1. Home
image

JavaScript Tutorial Concepts - From Beginner to Pro

Learn JavaScript from scratch! Our tutorial covers basics to advanced concepts. Start learning today!

  • 24
  • 9 Hours
right-top-arrow
17

OOP in JavaScript

Updated on 09/08/2024253 Views

Object-oriented programming in JavaScript is one of the types of programming supported by JavaScript. It deals with objects and classes and allows us to write more manageable and reusable code. The OOP in JavaScript concept has helped me time and time again to write efficient and clean code.

This JavaScript object oriented programming tutorial is sure to give you a basic idea about it. I will try to include as many oops concepts in JavaScript with example as I can to give a better understanding.

What Is an Object?

JavaScript is an object oriented language but what does an object mean? Before we delve deeper into JavaScript object oriented concepts, let me explain what exactly an object is.

In object-oriented programming (OOP), an object is an instance of a class. This means, it represents a real-world entity or concept and includes both data (attributes or properties) and activity (methods or functions) associated with that entity. Say for example if we take a class to be Fruits, an apple can be an object of the class.

Now let me discuss some key features of JavaScript below.

  • Instance of a class: A class is a blueprint of an object. This means an object is based on a class and shares some common features with the class.
  • Properties: Objects have properties that include data about the object. These properties can be variables that describe the object's qualities, such as a person's name, age, or address.
  • Methods: Objects have methods that define the activities or operations that they can execute. These methods are functions that handle the object's data or interact with other objects.

Now let me show a JavaScript OOP example to explain how objects work.

// Class definition

class Person {

constructor(name, age) {

this.name = name;

this.age = age;

}

sayHello() {

console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);

}

}

// Object instantiation

let person_1 = new Person('Ali', 32);

let person_2 = new Person('Bobby', 26);

// Using objects and calling methods

person_1.sayHello(); // Output: Hello, my name is Ali and I'm 32 years old.

person_2.sayHello(); // Output: Hello, my name is Bob and I'm 26 years old.

In the above example, both person_1 and person_2 are objects. They both belong to the Person class. Each of them has individual data(name and age) and method(sayHello).

What Is a Class?

Now that we know what an object is, let me tell you about classes. In object-oriented programming JavaScript, a class is a blueprint or template for object creation. It specifies the properties and methods that objects in that class will have. Classes help to organize and structure code by encapsulating related data and functions into a single unit.

Now let me share with you some features of classes with respect to JavaScript OOP methods.

  • Blueprint of an object: A class describes the structure and behavior of objects within that class and thus is called the blueprint of an object. It outlines the features that each object will have, as well as the methods that may be used for changing those properties.
  • Instantiation: Instantiation is the process of creating objects inside classes. Each object formed from the same class has the same structure and behavior as the class, but it can have unique and individual data values.
  • Properties: Classes also have properties or attributes that show the link with the objects within that class. These properties may be variables that contain information about the object, such as a person's name, age, or address.
  • Methods: Classes have methods that define the actions or processes that their objects can do. These methods are functions that can modify the object's data, interact with other objects, and provide additional functionality.

To understand the concept of classes better, let me share a JavaScript OOP example.

// Class definition

class Fruits {

// Constructor to initialize properties

constructor(name, price) {

this.name = name;

this.price = price;

}

// Method to greet

Fruit_1() {

console.log(`The name of the fruit is ${this.name} and its price is ${this.price} .`);

}

}

// Creating objects using the class

let apple = new Fruits('apple', 120);

let banana = new Fruits('banana', 100);

// Using objects and calling methods

apple.Fruit_1(); // Output:The name of the fruit is apple and its price is 120.

banana.Fruit_1(); // Output:The name of the fruit is banana and its price is 100.

In the above example, I have defined a class called Fruits with properties named name and price. Fruit_1 is a method of the class Fruits. Then we have created two instances of the class called apple and banana with their individual attributes. Finally, we have used the method Fruit_1 on both objects.

What Exactly Is Object-Oriented Programming?

Object-oriented programming is a type of programming that uses the concept of objects. The individual objects contain data and methods. There are four main concepts in object-oriented programming namely.

Encapsulation

Encapsulation in object-oriented programming includes combining data and methods that interact with the data into a single unit, often an object. This helps to organize and structure code by hiding an object's internal state and offering controlled access to its attributes and operations via interfaces.

Encapsulation has several advantages. Let me explain some of them here.

  • Access control: We can use encapsulation to provide controlled access to the properties and methods of an object. We can use access specifiers like public, private, and protected which allow us to customize exactly how much information can be accessed outside the object.
  • Modularity: Using encapsulation, we can group related data in an object. This helps with managing the code later.
  • Data hiding: Encapsulation helps with privacy and protects specific parts of the code from being bare. This increases safety and reduces bugs.

Inheritance

Inheritance is a fundamental concept in object-oriented programming that enables the reuse of data and methods and facilitates hierarchical relationships between classes, promoting code reusability.

Some features of inheritance are as follows:

  • Parent-child relationship: Inheritance is a connection between two classes in which one class which is the child or subclass inherits properties and methods from the parent or superclass. The kid class is said to have developed from the parent class.
  • Code reusability: Inheritance p[romortes code reusability. This is because we do not have to write the same code over and over again for different objects. We can just make the classes inherit the properties of another class using the concept of inheritance.
  • Method overriding: Inheritance allows subclasses or child classes to redefine methods inherited from the superclass or parent class. This means that a subclass can declare its own implementation of a method, which takes priority over the method described in the superclass when called from the subclass.

Let me share a JavaScipt OOP function to demonstrate inheritance.

Code:

// Parent class or Superclass

class Vehicle {

constructor(make, model) {

this.make = make;

this.model = model;

}

start() {

console.log('Start the vehicle.');

}

}

// Child class or derived class

class Car extends Vehicle {

drive() {

console.log('Drive the car.');

}

}

// Creating instances of classes or object

let myCar = new Car('Fiesta', 'Ford');

myCar.start(); // Inherited method from Vehicle class

myCar.drive(); // Method specific to Car class

In the above example, the Car class inherits the start method from the Vehicle class using inheritance, showing the concept of code reusability and hierarchical relationships in OOP.

Polymorphism

The concept of Polymorphism in object-oriented programming means that a program might have different objects that share the same name but show different properties when called in a different context. It allows us to use objects in different classes and access them as if they belong to one superclass.

Let me now discuss some key features of polymorphism here.

  • Method overloading: Polymorphism allows a single method name to be applied to many methods that have different parameter lists. This is referred to as method overloading.
  • Dynamic binding: Polymorphism includes dynamic or late binding, in which a suitable method implementation is decided at runtime using the object's true type rather than its reference type. This provides flexibility and adaptability in code execution.
  • Interface: In object-oriented programming, interfaces or abstract classes are usually used to accomplish polymorphism. Objects of various classes that implement the same interface or derive from the same abstract class can be treated similarly, allowing for interchangeability.

Let me show you how polymorphism works with the help of a JavaScript object oriented programming example.

Code:

// Shape superclass with a draw method

class Shape {

draw() {

console.log('Draw a shape.');

}

}

// Square subclass that overrides the draw method in shape class

class Square extends Shape {

draw() {

console.log('Drawing a Square.');

}

}

// Circle subclass that overrides the draw method

class Circle extends Shape {

draw() {

console.log('Drawing a Circle.');

}

}

// Using polymorphism with different shape objects

let shape1 = new Square();

let shape2 = new Circle();

shape1.draw(); // Output: Drawing a Square.

shape2.draw(); // Output: Drawing a Circle.

In this example, both the Square and Circle classes override the draw method inherited from the Shape superclass, exhibiting polymorphic behavior in which the same method (draw) is executed differently depending on the object type (Circle or Square).

Final Words

As we have learned from this tutorial, the object-oriented programming concept is a core pillar of JavaScript programming. It helps us write clean code and reduces bugs.

This tutorial was aimed to teach the basic JavaScript oops concepts. If you want to learn the more advanced oop in JavaScript concepts, I would recommend checking out courses from upGrad.

Their courses are in collaboration with some of the best universities around the world. The courses are also curated by the best professors in the field.

Frequently Asked Questions

  1. What is object-oriented programming language in JavaScript?

OOP in JavaScript is a style of programming in which code revolves around objects that include attributes and methods, allowing for efficient and reusable code. Classes, inheritance, encapsulation, and polymorphism are examples of OOP concepts in JavaScript that help to structure and manage code complexity.

  1. Can you write OOP in JavaScript?

Yes, you can build object-oriented programming (OOP) code in JavaScript by employing classes, inheritance, encapsulation, and polymorphism to construct modular, reusable, organized code.

  1. Why OOP is not used in JavaScript?

OOP is widely utilized in JavaScript, particularly after the introduction of ES6 and the availability of classes.

  1. What are the 4 concepts of OOP in JavaScript?

The four main concepts of OOP in JavaScript are polymorphism, data abstraction, encapsulation, and inheritance.

  1. How many OOPs are there in JavaScript?

JavaScript has only one fundamental object-oriented programming (OOP) method, which includes the use of objects, classes (introduced in ES6), inheritance, encapsulation, and polymorphism.

  1. What is the basic concept of OOP?

The fundamental idea behind OOP in JavaScript is to arrange code around objects that contain both methods and attributes. This increases the modularity, and reusability of the code.

  1. What are the 4 types in OOPs?

The four types of OOP in JavaScript are as follows.

  • Polymorphism
  • Data abstraction
  • Inheritance
  • Encapsulation
  1. What is the full form of OOPs?

The full form of OOPs is Object Oriented Programming Systems..

  1. What are the 8 types of JavaScript?

The eight types of JavaSCript are as follows.

  • Client-side JavaScript
  • Server-side JavaScript
  • Core JavaScript
  • Frameworks and Libraries
  • Mobile Development
  • Desktop Applications
  • Embedded JavaScript
mukesh

mukesh

Working with upGrad as a Senior Engineering Manager with more than 10+ years of experience in Software Development and Product Management.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...