In JavaScript, a class is a blueprint for creating objects with similar properties and methods. It provides a way to define a particular type of object, encapsulating data for the object and methods to operate on that data. Classes were introduced in ECMAScript 2015 (ES6) to mimic the class-based inheritance found in other object-oriented programming languages.
How to Define a Class
Here's how you define a class in JavaScript: JAVASCRIPT
class MyClass {
constructor(prop1, prop2) {
this.property1 = prop1;
this.property2 = prop2;
}
method1() {
console.log('Method 1 executing');
}
method2() {
console.log('Method 2 executing');
}
}
In this example:
>
MyClass is the name of the class.>
constructor is a special method for creating and initializing objects created with a class. It is executed automatically when a new object is created with the new keyword. >
method1 and method2 are methods of the class, defining behaviour for instances of the class. Creating an Instance
To create an instance of a class, you use thenew keyword:
JAVASCRIPT
const obj = new MyClass('value1', 'value2');
This creates a new object
obj based on the MyClass blueprint, with property1 set to 'value1' and property2 set to 'value2'. Accessing Properties and Methods
You can then access properties and methods of the object using dot notation: JAVASCRIPT
console.log(obj.property1); // Output: 'value1'
obj.method1(); // Output: 'Method 1 executing'Inheritance
Classes in JavaScript also support inheritance. You can use theextends keyword to create a subclass:
JAVASCRIPT
class SubClass extends MyClass {
constructor(prop1, prop2, prop3) {
super(prop1, prop2);
this.property3 = prop3;
}
method3() {
console.log('Method 3 executing');
}
}
Happy coding!

