In JavaScript, a class is a blueprint for creating objects with shared structure and behavior. Classes make it easier to create multiple similar objects and organize code using object-oriented programming (OOP) principles.
There are two ways to create class. One by declaration and another by expression.
// class className {} - by declaration
// const className = class {} - by expression
// Declaration
class Person {
name = "Ram";
age = 25;
location = "Kathmandu";
greet () {
return "Good Morning";
}
}
// Expression; the class is anonymous but assigned to a variable
const Person = class {
name = "Ram";
age = 25;
location = "Kathmandu";
greet () {
return "Good Morning";
}
}
Think of a class like a blueprint for a house.
Using new, you build actual houses (objects) from that blueprint.
const objectName = new ClassName(arguments);
const Person = class {
name = "Ram";
age = 25;
location = "Kathmandu";
greet () {
return "Good Morning";
}
}
const person1 = new Person();
console.log(person1.name);
console.log(person1.age);
console.log(person1.location);
console.log(person1.greet());
A constructor is a special method inside a class that automatically runs when you create an object using new.
It is mainly used to initialize (set) properties of the object.