Classes and Objects in JavaScript — ES6 OOP Guide | Tutorials Logic
Classes in JavaScript
Classes were introduced in ES6 to make object-oriented code easier to read and organize. A class acts like a blueprint for creating objects. It describes what data an object should have and what actions that object can perform. Under the hood, JavaScript still uses prototypes, but the class syntax gives us a cleaner and more familiar way to work with reusable object structures.
A class can contain a constructor() method for initializing values, as well as instance methods that are available on every object created from that class. When we create an object using the new keyword, JavaScript builds a new instance and binds this to that object.
class Song {
constructor(name, artist) {
this.name = name;
this.artist = artist;
}
play() {
console.log(this.name + " by " + this.artist + " is playing.");
}
}
const mySong = new Song("Skyline", "Anaya");
mySong.play();
Constructors and Instance Methods
The constructor runs automatically whenever a new object is created from a class. It is commonly used to assign values such as names, prices, status flags, or configuration settings. Instance methods are shared by all objects of that class, which avoids duplicating the same function for every object.
class User {
constructor(name, email) {
this.name = name;
this.email = email;
}
introduce() {
return "Hi, I am " + this.name;
}
}
const user1 = new User("Riya", "riya@example.com");
console.log(user1.introduce());
Inheritance with extends and super()
JavaScript classes support inheritance, which means one class can reuse the behavior of another class. A child class uses the extends keyword, and when it has its own constructor, it should call the parent constructor using super() before using this.
class Course {
constructor(title) {
this.title = title;
}
getDetails() {
return "Course: " + this.title;
}
}
class PaidCourse extends Course {
constructor(title, price) {
super(title);
this.price = price;
}
getPriceTag() {
return "Price: Rs. " + this.price;
}
}
const jsCourse = new PaidCourse("JavaScript Mastery", 999);
console.log(jsCourse.getDetails());
console.log(jsCourse.getPriceTag());
Static Methods and Utility Logic
Sometimes a method belongs to the class itself rather than to individual objects. In that case, we use the static keyword. Static methods are helpful for utility functions, validation helpers, or factory methods that create instances in a special way.
class Temperature {
static toFahrenheit(celsius) {
return (celsius * 9) / 5 + 32;
}
}
console.log(Temperature.toFahrenheit(25)); // 77
Getters and Setters
Getters and setters let us control how values are read or updated. They are useful when you want to validate input or derive a formatted value without exposing all internal details directly.
class Product {
constructor(name, price) {
this.name = name;
this._price = price;
}
get price() {
return "Rs. " + this._price;
}
set price(value) {
if (value > 0) {
this._price = value;
}
}
}
const pen = new Product("Pen", 20);
pen.price = 25;
console.log(pen.price);
Objects in JavaScript
An object is a collection of key-value pairs. It is one of the most important building blocks in JavaScript because it allows us to model real-world entities such as users, products, courses, or settings. Each property describes some data, and methods describe behavior.
Objects can be created using an object literal, which is the most common and readable approach, or by using the new Object() constructor. In modern JavaScript, object literals are preferred for most cases.
Creating Objects
const student = {
name: "Aman",
course: "JavaScript",
isEnrolled: true,
greet() {
console.log("Welcome, " + this.name);
}
};
student.greet();
Accessing and Updating Object Properties
Object properties can be accessed using dot notation or bracket notation. Dot notation is simple and readable, while bracket notation is useful when the property name is stored in a variable or contains spaces or special characters.
const user = {
name: "Neha",
age: 24
};
console.log(user.name); // Neha
console.log(user["age"]); // 24
user.city = "Delhi";
user.age = 25;
console.log(user);
Nested Objects and Methods
Objects can contain other objects and arrays. This is how JavaScript stores structured data such as user profiles, API responses, shopping carts, and configuration objects. Methods can also use this to refer to values within the same object.
const profile = {
name: "Rohit",
skills: ["HTML", "CSS", "JavaScript"],
address: {
city: "Pune",
country: "India"
},
introduce() {
return this.name + " lives in " + this.address.city;
}
};
console.log(profile.introduce());
Object Utility Methods
JavaScript provides helper methods like Object.keys(), Object.values(), and Object.entries() to inspect object data. These are especially useful when we want to loop through all properties or convert object data into a format that is easier to work with.
const settings = {
theme: "light",
language: "en",
notifications: true
};
console.log(Object.keys(settings)); // ["theme", "language", "notifications"]
console.log(Object.values(settings)); // ["light", "en", true]
console.log(Object.entries(settings));
Classes vs Objects
An object is a single instance containing data and behavior. A class is a blueprint used to create many similar objects. If you only need one standalone structure, an object literal is often enough. If you need multiple similar entities with shared behavior, a class is usually the better choice.
Level Up Your Javascript Skills
Master Javascript with these hand-picked resources