Table of contents
1.
Introduction
2.
Features of OOP in JavaScript
2.1.
Objects
2.2.
Constructors:
2.3.
Classes
2.4.
Encapsulation
2.5.
Inheritance
3.
Is JavaScript Object-Oriented?
4.
What is an Object in JavaScript?
5.
No Classes in JavaScript
6.
JavaScript Encapsulation
7.
JavaScript Inheritance
8.
What is Polymorphism?
9.
JavaScript and OOP
10.
JavaScript objects support Association, Aggregation, and Composition
11.
How is JavaScript an OOP Language without Classes?
12.
Frequently Asked Questions
12.1.
1). Is Oops possible in JavaScript?
12.2.
2). Why do some of the developers not consider JavaScript as an object oriented language?
12.3.
3). What is an object in JavaScript?
12.4.
4). How can we create objects in JavaScript?
12.5.
5). What is the difference between function and object in JavaScript?
13.
Conclusion
Last Updated: Oct 16, 2024
Easy

Object Oriented Programming In JavaScript

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Javascript is a programming language that is widely used for web development. In this blog, we will explore some of the important concepts on object-oriented mechanisms that are supported by JavaScript.

 

Before moving on to the topics let us see what kind of questions are asked in JavaScript interviews related to oop:

 

  • How object-oriented programming concepts are implemented in JavaScript? 
  • How did JavaScript differ from other programming languages?
  • How would you implement inheritance in JavaScript?

So, to find out the answers, read the blog till the end. Let’s begin!

Also Read, Javascript hasOwnProperty

Features of OOP in JavaScript

Some of the important object-oriented features in JavaScript are:

  1. Object
  2. Classes
  3. Encapsulation
  4. Inheritance

 

Let us discuss the above features one by one and practice them on the JS compiler.

Objects

An object is a unique entity in JavaScript which contains various properties and methods. Let us consider an example, “car” is a real-life object, which has characteristics like the model, type, colour, horsepower and also performs certain actions like driving.

 

The above characteristics of an object are known as the property of that object in oops, and the actions are called methods in oops.

 

Objects are everywhere in the JavaScript programming language, either in the form of function, arrays and string. 

Let us consider an example for object:

//Defining object
let codingninjas = {
    course_1:'JAVA',
    course_2:'C++',
    course_3:'DBMS',
    Course_4:'Python'
  
    
}
console.log(codingninjas.course_1); 
console.log(codingninjas.course_2); 
console.log(codingninjas.course_3); 
console.log(codingninjas.course_4); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

JAVA
C++
DBMS
Python
You can also try this code with Online Javascript Compiler
Run Code

Constructors:

A constructor allows us to provide custom initialization to an instantiated object before any other methods can be called.

Let understand constructors with the help of an example:

function car(first_name,last_name){
  this.car_name = first_name;
  this.car_year = last_name;
}
//creating new instances of person object
let car1 = new car('BMW',2020);
let car2 = new car('Audi',2018);
  
console.log(car1.car_name +" "+car1.car_year);
console.log(car2.car_name +" "+car2.car_year);
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

BMW 2020
Audi 2018

 

Know What is Object in OOPs here in detail.

Classes

 

Classes are an overview of an object. A class can have many objects associated with it, because the class is a template of the object, while objects are instances of the class or the implementation of the class. 

 

A key point to be noted is, JavaScript is a prototype-based object-oriented language, which means it doesn’t have classes but it defines behaviours of a class using constructor function and then we reuse it using the prototype.

Example:

function Car(name,maker,engine){
    this.name = name,
    this.maker = maker,
    this.engine = engine
};
  
Car.prototype.getDetails = function(){
    console.log('The name of the car is '+ this.name);
}
  
let car1 = new Car('Altros','Suzuki','1340cc');
let car2 = new Car('Rk7','Rangerover','998cc');
  
console.log(car1.name);
console.log(car2.maker);
console.log(car1.getDetails());
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

Altros
Range Rover
The name of the car is Altros
You can also try this code with Online Javascript Compiler
Run Code

Encapsulation

It deals with wrapping property and function in a single unit. Let us look at one example:

class car{
    constructor(name,id){
        this.name = name;
        this.id = id;
    }
    add_fueltype(add){
        this.add = add;
    }
    getDetails(){
        console.log(`Name is ${this.name},Fuel-type is: ${this.add}`);
    }
}
  
let car1 = new car('BMW',21);
car1.add_fueltype('Petrol');
car1.getDetails();
You can also try this code with Online Javascript Compiler
Run Code

 

Output

Name is BMW, Fuel-type is: Petrol
You can also try this code with Online Javascript Compiler
Run Code

 

In the above example, we created a car object using the constructor. Then we have  Initialized its property, and we have used its functions. We are not bothered about the implementation details of the code. 

 

We are simply working with an object interface without considering the implementation details. 

Inheritance

It is a concept in which the property and methods of an object are being used by another object by the means of inheritance. In JavaScript, an object inherits an object i.e. certain features (property and methods) of one object can be reused by other objects in JavaScript. 

 

Example:

class vehicle{
    constructor(name){
        this.name = name;
    }
    //method to return the string
    toString(){
        return (`Name of vehicle: ${this.name}`);
    }
}
class car extends vehicle{
    constructor(name,id){
        //super keyword to for calling above class constructor
        super(name);
        this.id = id;
    }
    toString(){
        return (`${super.toString()},Car Id: ${this.id}`);
    }
}
let car1 = new car('BMW',22);
console.log(car1.toString());
You can also try this code with Online Javascript Compiler
Run Code

 

Output

Name of Vehicle: BMW, Car Id: 22

 

In the above example, we define a vehicle object with certain property and method, and then we inherit the vehicle object in the car object and use all the properties and methods of the vehicle object as well define certain properties and methods for the car. 

Must Read Fibonacci Series in JavaScript

Is JavaScript Object-Oriented?

  • JavaScript follows Object-Oriented Programming (OOP) principles.
     
  • Objects in JavaScript are used to model real-world entities.
     
  • Although JavaScript doesn't have traditional classes like other OOP languages, it uses prototypes.
     
  • It supports core OOP concepts such as inheritance, encapsulation, and polymorphism.

What is an Object in JavaScript?

An object in JavaScript is a standalone entity that contains properties and methods. These properties can hold values (data), while methods are functions that allow the object to perform tasks. Objects are used to represent real-world entities such as people, cars, or user profiles. Objects in JavaScript can be created in multiple ways:

  1. Object Literals
let car = {
 make: "Toyota",
 model: "Camry",
 year: 2020,
 drive: function() {
   console.log("The car is driving");
 }
};
You can also try this code with Online Javascript Compiler
Run Code

 

Constructor Functions:

function Car(make, model, year) {
 this.make = make;
 this.model = model;
 this.year = year;
}
let myCar = new Car("Toyota", "Camry", 2020);
You can also try this code with Online Javascript Compiler
Run Code

 

ES6 Classes (syntactic sugar for prototype-based inheritance):

class Car {
 constructor(make, model, year) {
   this.make = make;
   this.model = model;
   this.year = year;
 }
}
let myCar = new Car("Toyota", "Camry", 2020);
You can also try this code with Online Javascript Compiler
Run Code

Objects are at the core of JavaScript and help organize code for better reusability and maintainability.

No Classes in JavaScript

Before ES6, JavaScript did not have the class structure that is common in other OOP languages like Java or C++. Instead, it relied on prototypes for inheritance. Even though ES6 introduced a class keyword, it is just syntactic sugar over JavaScript's existing prototype-based system. This means that, internally, JavaScript is still using prototypes rather than classes to manage inheritance and object creation.

For example, before ES6:

function Person(name, age) {
 this.name = name;
 this.age = age;
}
Person.prototype.sayHello = function() {
 console.log(`Hello, my name is ${this.name}`);
};
let person1 = new Person("John", 30);
You can also try this code with Online Javascript Compiler
Run Code


In ES6, the same functionality can be achieved using classes:

class Person {
 constructor(name, age) {
   this.name = name;
   this.age = age;
 }
 
 sayHello() {
   console.log(`Hello, my name is ${this.name}`);
 }
}
let person1 = new Person("John", 30);
You can also try this code with Online Javascript Compiler
Run Code

JavaScript Encapsulation

Encapsulation refers to the concept of bundling data (variables) and methods (functions) that operate on the data into a single unit, typically an object. JavaScript supports encapsulation by allowing you to hide the internal details of objects from the outside world. You can achieve encapsulation in JavaScript in the following ways:

Closures: You can use closures to create private variables in JavaScript:

function Person(name) {
 let age = 25; // Private variable
 this.name = name;
 
 this.getAge = function() {
   return age;
 };
}
let person1 = new Person("John");
console.log(person1.getAge()); // 25
console.log(person1.age); // undefined (cannot access directly)
You can also try this code with Online Javascript Compiler
Run Code


Symbols: Symbols can also be used to hide object properties:

let privateProp = Symbol("private");
let obj = {
 [privateProp]: "This is a private property"
};
console.log(obj[privateProp]); // Access possible through Symbol
console.log(obj.privateProp); // undefined
You can also try this code with Online Javascript Compiler
Run Code


Encapsulation in JavaScript helps in improving code security and robustness.

JavaScript Inheritance

JavaScript uses prototypal inheritance to allow objects to inherit properties and methods from other objects. Every object in JavaScript has an internal [[Prototype]] property that points to another object (known as the prototype). This chain continues until it reaches null, which acts as the end of the prototype chain.

function Animal(name) {
  this.name = name;
}

Animal.prototype.speak = function() {
  console.log(`${this.name} makes a noise`);
};

function Dog(name) {
  Animal.call(this, name); // Inherit properties
}

Dog.prototype = Object.create(Animal.prototype); // Inherit methods
Dog.prototype.constructor = Dog;

Dog.prototype.speak = function() {
  console.log(`${this.name} barks`);
};

let dog1 = new Dog("Rex");
dog1.speak(); // Rex barks
You can also try this code with Online Javascript Compiler
Run Code

Here, the Dog class inherits from Animal, and we have overridden the speak method.

What is Polymorphism?

Polymorphism refers to the ability of different objects to respond to the same method or function call in different ways. In JavaScript, polymorphism is achieved primarily through method overriding and method overloading.

  • Method Overriding: Inheritance allows a subclass to provide a specific implementation of a method already defined in its superclass.
     
  • Method Overloading: JavaScript doesn't natively support method overloading like some other languages, but you can implement it by using different numbers of parameters or types within a method.

JavaScript and OOP

JavaScript is an object-oriented programming language, even though it doesn't follow traditional OOP structures. Instead of classes and inheritance hierarchies, JavaScript uses prototypes and objects to implement OOP concepts. By modeling data with objects and using functions as methods, JavaScript provides a flexible, dynamic approach to OOP.

With ES6, JavaScript introduced features like classes, which made it easier to write OOP-style code, although it is just a more intuitive syntax for prototype-based inheritance.

JavaScript objects support Association, Aggregation, and Composition

  • Association: Objects can be related, meaning one object uses or references another.
  • Aggregation: Objects can include other objects, but the child objects can exist independently.
  • Composition: Child objects are dependent on the parent object and can't exist separately.

How is JavaScript an OOP Language without Classes?

Even though JavaScript did not initially support classes (pre-ES6), it is still considered an OOP language because it supports the key OOP principles—encapsulation, inheritance, and polymorphism—through its prototype-based system. JavaScript objects inherit properties from other objects, and these objects can contain both data (properties) and behavior (methods), enabling OOP-like structures without traditional classes.

With the introduction of the ES6 class syntax, JavaScript OOP has become easier to implement, making it more accessible to developers familiar with classical OOP languages.

Frequently Asked Questions

1). Is Oops possible in JavaScript?

Answer: Yes, JavaScript supports inheritance through prototyping, properties and methods. It also supports polymorphism, encapsulation and many sub-classing paradigms.

2). Why do some of the developers not consider JavaScript as an object oriented language?

Answer: Many developers do not consider JavaScript a true object-oriented language due to its lack of class concept and because it does not enforce compliance with OOP principles.

3). What is an object in JavaScript?

Answer: In JavaScript, an object is a standalone entity, with properties and type.

4). How can we create objects in JavaScript?

Answer: Use the new keyword with Object() constructor to create objects in JavaScript.

For example: const person = new Object(); 

5). What is the difference between function and object in JavaScript?

Answer: Functions are first-class objects in JavaScript because they have the same attributes and methods as any other object. Functions may be called, which sets them apart from other objects. They are, in a nutshell, Function objects.

Conclusion

In this blog, we discussed key Object-Oriented Programming (OOP) concepts in JavaScript through various examples, covering topics like constructors, classes, encapsulation, and inheritance. These examples demonstrate how JavaScript implements OOP principles to build scalable and maintainable code.

Recommended Readings:

If you want to learn more about front end web development, Coding Ninjas is offering the best courses, you can check it out here.

Happy Learning!

 

Live masterclass