Object-Oriented Programming (OOP) is a programming approach that organizes code around objects. Objects combine data and behavior, making it easier to represent real-world entities and build applications with reusable, organized code.
JavaScript supports object-oriented programming through objects, classes, constructors, methods, and properties. These concepts are useful when developing applications such as e-commerce websites, banking systems, games, and user management systems.
In this tutorial, you will learn the fundamentals of JavaScript OOP, including how to create objects, define classes, initialize objects with constructors, create methods, and work with properties.
What Is OOP in JavaScript?
Object-Oriented Programming is a programming paradigm in which programs are designed around objects that contain data and functionality.
For example, a student can be represented as an object with properties such as name, age, and course. The object can also have methods such as displaying student details.
JavaScript supports OOP using objects directly and through class syntax.
Example of OOP in JavaScript
const student = {
name: "Karim",
age: 22,
introduce() {
console.log(`My name is ${this.name}.`);
}
};
student.introduce();
Output:
My name is Karim.
In this example:
studentis an object.nameandageare properties.introduce()is a method.this.nameaccesses thenameproperty of the object when the method is called asstudent.introduce().
OOP helps you group related data and behavior in one place instead of keeping everything separate.
Objects in JavaScript
An object is a collection of properties. Each property has a key and a value. A property value can be a string, number, boolean, array, another object, or function.
Objects allow you to represent entities with related information.
Creating an Object
You can create an object using object literal syntax.
const car = {
brand: "Toyota",
model: "Camry",
year: 2025
};
console.log(car.brand);
console.log(car.model);
console.log(car.year);
Output:
Toyota
Camry
2025
Here, car contains three properties: brand, model, and year.
Accessing Object Properties
You can access an object’s properties using dot notation or bracket notation.
const employee = {
name: "Ahmed",
salary: 30000
};
console.log(employee.name);
console.log(employee["salary"]);
Output:
Ahmed
30000
Dot notation is convenient when the property name is known. Bracket notation is useful when the property name is stored in a variable or contains characters that cannot be used in dot notation.
Learn more about JavaScript Objects.
Objects Can Contain Methods
An object can contain both data and behavior.
const calculator = {
add(a, b) {
return a + b;
},
subtract(a, b) {
return a - b;
}
};
console.log(calculator.add(10, 5));
console.log(calculator.subtract(10, 5));
Output:
15
5
The calculator object stores two methods that perform calculations.
Classes in JavaScript
A class is a template for creating objects with a shared structure and behavior. JavaScript introduced class syntax in ECMAScript 2015 (ES6).
Classes make it easier to create multiple objects with similar properties and methods.
Creating a Class
Use the class keyword to define a class.
class Student {
display() {
console.log("Student details");
}
}
const student1 = new Student();
student1.display();
Output:
Student details
In this example:
class Studentdefines a class.display()defines a method.new Student()creates an instance of the class.student1.display()calls the method.
Creating Multiple Objects from a Class
You can create multiple instances from the same class.
class Student {
constructor(name, course) {
this.name = name;
this.course = course;
}
display() {
console.log(`${this.name} studies ${this.course}.`);
}
}
const student1 = new Student("Karim", "JavaScript");
const student2 = new Student("Ahmed", "Python");
student1.display();
student2.display();
Output:
Karim studies JavaScript.
Ahmed studies Python.
Both objects use the same class definition, but each instance has its own name and course values.
Why Use Classes?
Classes are useful when you need to create multiple objects that share common behavior.
Common examples include:
- Creating student records.
- Representing products in an online store.
- Managing employee information.
- Building game characters.
- Modeling bank accounts.
JavaScript classes provide a clearer syntax for object creation and inheritance. They use JavaScript’s prototype-based object system underneath.
Constructors in JavaScript
A constructor is a special method in a JavaScript class that initializes a newly created instance.
The constructor runs automatically when you create an instance using the new keyword.
Example of a Constructor
class Car {
constructor(brand, color) {
this.brand = brand;
this.color = color;
}
}
const car1 = new Car("Toyota", "Black");
console.log(car1.brand);
console.log(car1.color);
Output:
Toyota
Black
The constructor receives "Toyota" and "Black" as arguments and assigns them to the new object’s properties.
Understanding the Constructor
constructor(brand, color) {
this.brand = brand;
this.color = color;
}
constructor()is the special class method.brandandcolorare parameters.this.brandandthis.colorrefer to properties of the instance being initialized.- The assignments store the supplied values on the new object.
A class can have only one constructor method.
Constructor with Default Values
You can provide default parameter values when an argument is omitted or explicitly passed as undefined.
class User {
constructor(name = "Guest", role = "Visitor") {
this.name = name;
this.role = role;
}
}
const user1 = new User("Karim", "Developer");
const user2 = new User();
console.log(user1.name, user1.role);
console.log(user2.name, user2.role);
Output:
Karim Developer
Guest Visitor
The first instance receives the supplied values. The second instance uses the default values.
Why Are Constructors Useful?
Constructors help initialize objects consistently. They allow you to supply the data each instance needs when it is created.
Without a constructor, you might have to create an object and assign its properties separately each time.
Methods in JavaScript
A method is a function associated with an object. Methods define actions that an object can perform.
In a class, you can define methods that are available to its instances through the class prototype.
Creating a Method
class Person {
greet() {
console.log("Hello, welcome!");
}
}
const person1 = new Person();
person1.greet();
Output:
Hello, welcome!
The greet() method defines behavior that instances of Person can use.
Methods with Parameters
Methods can accept parameters and use instance properties.
class Calculator {
add(a, b) {
return a + b;
}
multiply(a, b) {
return a * b;
}
}
const calculator = new Calculator();
console.log(calculator.add(5, 3));
console.log(calculator.multiply(5, 3));
Output:
8
15
The methods receive arguments and return the calculated results.
Methods Using this
The this keyword usually refers to the instance when a class method is called through that instance.
class Employee {
constructor(name, salary) {
this.name = name;
this.salary = salary;
}
displayDetails() {
console.log(`Name: ${this.name}`);
console.log(`Salary: ${this.salary}`);
}
}
const employee1 = new Employee("Karim", 30000);
employee1.displayDetails();
Output:
Name: Karim
Salary: 30000
When employee1.displayDetails() is called, this.name and this.salary refer to properties on employee1.
Remember that this depends on how a method is called. Extracting a class method and calling it without its instance as the receiver can result in this being undefined in class methods.
Properties in JavaScript
Properties store information associated with an object. They describe the object’s state or characteristics.
For example, a product might have properties such as name, price, and quantity.
Creating Properties in a Class
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
const product1 = new Product("Laptop", 50000);
console.log(product1.name);
console.log(product1.price);
Output:
Laptop
50000
Here, name and price are instance properties.
Accessing and Updating Properties
You can read or update an object’s properties after creating an instance.
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
const product1 = new Product("Phone", 20000);
console.log(product1.price);
product1.price = 18000;
console.log(product1.price);
Output:
20000
18000
The first statement displays the original price. The assignment changes the instance’s price property, so the next statement displays the updated price.
Adding a Property After Object Creation
JavaScript objects are generally extensible by default, so you can add new properties to an existing instance.
class User {
constructor(name) {
this.name = name;
}
}
const user1 = new User("Karim");
user1.city = "Hyderabad";
console.log(user1.name);
console.log(user1.city);
Output:
Karim
Hyderabad
The city property was added after the object was created. In larger applications, it is often helpful to initialize expected properties consistently in the constructor.
Complete Example of OOP in JavaScript
The following example combines objects, classes, constructors, methods, and properties into a simple bank account program.
class BankAccount {
constructor(owner, balance) {
this.owner = owner;
this.balance = balance;
}
deposit(amount) {
this.balance += amount;
console.log(`Deposited: ${amount}`);
}
displayBalance() {
console.log(`${this.owner}'s balance: ${this.balance}`);
}
}
const account1 = new BankAccount("Karim", 1000);
account1.displayBalance();
account1.deposit(500);
account1.displayBalance();
Output:
Karim's balance: 1000
Deposited: 500
Karim's balance: 1500
How This Example Works
BankAccountis the class.constructor()initializes the account.ownerandbalanceare instance properties.deposit()anddisplayBalance()are methods.account1is an instance created from the class.thisrefers to the account instance when its methods are called throughaccount1.
This example demonstrates how OOP combines data and behavior in a reusable structure.
For a real banking application, you would also validate deposit amounts and protect account state against invalid changes.
Difference Between Objects, Classes, Constructors, Methods, and Properties
| Concept | Meaning | Example |
|---|---|---|
| Object | A collection of related properties | const user = { name: "Karim" } |
| Class | A template for creating instances | class User {} |
| Constructor | Initializes a new instance | constructor(name) { ... } |
| Method | A function associated with an object or class | greet() { ... } |
| Property | Stores information associated with an object | this.name = name |
These concepts work together to make object-oriented JavaScript easier to organize and maintain.
Advantages of OOP in JavaScript
Object-oriented programming offers several benefits when designing applications.
Code reusability: You can create multiple instances from one class definition.
Organization: Related data and behavior can be grouped together.
Maintainability: Changes to shared methods can be made in one place.
Modeling real-world entities: Objects can represent users, products, accounts, and other entities.
Extensibility: Classes can be extended using inheritance when related objects need to share or specialize behavior.
OOP is not required for every JavaScript application. Small scripts may be simpler with functions and plain objects, while classes can be useful for more complex models.
FAQs About JavaScript OOP Fundamentals
What is OOP in JavaScript?
OOP is a programming approach that organizes code around objects containing data and behavior. JavaScript supports OOP using objects, classes, constructors, methods, and inheritance.
What is an object in JavaScript?
An object is a collection of properties, each consisting of a key and a value. Its properties can store data or functions.
What is a class in JavaScript?
A class defines a structure and behavior that can be shared by multiple instances.
What is a constructor in JavaScript?
A constructor is a special method that initializes an instance when it is created using the new keyword.
What is a method in JavaScript?
A method is a function associated with an object or class. It defines an action that the object can perform.
What is a property in JavaScript?
A property is a key-value entry associated with an object. Properties commonly store information such as a user’s name, a product’s price, or an account’s balance.
What is the difference between a class and an object?
A class defines a reusable structure, while an object is an actual collection of properties and behavior. An instance created using new is an object associated with a class.
Is JavaScript a class-based or prototype-based language?
JavaScript is prototype-based. Its class syntax provides a convenient way to define constructors, methods, and inheritance using the prototype system.
Conclusion
JavaScript OOP fundamentals help you organize programs around objects that combine data and behavior. Objects store information, classes provide a reusable structure, constructors initialize instances, methods define actions, and properties represent object state.
By understanding these concepts, you can begin building more organized JavaScript applications and prepare for advanced OOP topics such as inheritance, encapsulation, polymorphism, getters, setters, and static methods.