Category: javascript
OOPS in JavaScript
Published on 16 Jun 2026
Explanation
OOPS (Object-Oriented Programming System)
in JavaScript
is a programming paradigm based on
objects and classes. The four main
principles are Encapsulation, Inheritance,
Polymorphism, and
Abstraction.
Code:
class Car {
constructor(brand) {
this.brand = brand;
}
display() {
console.log(`Brand: ${this.brand}`);
}
}
const car = new Car('Toyota');
car.display();
Explanation
Encapsulation is the process of bundling
data and methods within a class
and controlling access to internal data.
Code:
class Employee {
#name;
setName(name) {
this.#name = name;
}
getName() {
return this.#name;
}
}
const emp = new Employee();
emp.setName('John');
console.log(emp.getName());
Explanation
Inheritance allows a class to inherit
properties and methods from another class,
promoting code reuse.
Code:
class Animal {
sound() {
console.log('Animal makes a sound');
}
}
class Dog extends Animal {
bark() {
console.log('Dog barks');
}
}
const dog = new Dog();
dog.sound();
dog.bark();
Explanation
Polymorphism allows the same method to
behave differently depending on the object
that invokes it.
Code:
class Animal {
sound() {
console.log('Animal sound');
}
}
class Dog extends Animal {
sound() {
console.log('Dog barks');
}
}
const animal = new Dog();
animal.sound();
Explanation
Abstraction hides implementation details
and exposes
only the necessary functionality to the
user.
Code:
class Shape {
draw() {
throw new Error('draw() method must
be implemented');
}
}
class Circle extends Shape {
draw() {
console.log('Drawing Circle');
}
}
const shape = new Circle();
shape.draw();