Classes In JavaScript

Classes in JavaScript are a blueprint for creating objects, introduced in ES6. They encapsulate data and behavior by defining properties and methods, enabling object-oriented programming. Classes simplify the creation of objects and inheritance, making code more organized and reusable.

Class In JavaScript

Classes are similar to functions. Here, a class keyword is used instead of a function keyword. Unlike functions classes in JavaScript are not hoisted. The constructor method is used to initialize. The class name is user-defined.

Syntax:

class classname {
constructor(parameter) {
this.classname = parameter;
}
}

Constructor Method

The constructor method in JavaScript is a special method used for initializing objects created with a class.

It’s called automatically when a new instance of the class is created. It typically assigns initial values to object properties using parameters passed to it. This ensures objects are properly initialized upon creation.

Syntax:

class ClassName {
  constructor() { ... }
  method() { ... }
}

Example 1: The below example illustrates the JavaScript classes.

JavaScript
class emp {
    constructor(name, age) {
        this.name = name;
        this.age = age;

    }
}
const emp1 = new emp("Geek1", "25 years");
console.log(emp1.name);
console.log(emp1.age);

Output
Geek1
25 years

Example 2: This example demonstrates the use of constructor to create class in JavaScript.

Javascript
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

const person1 = new Person("Alice", 30);
console.log(person1.name); // Output: Alice
console.log(person1.age);  // Output: 30

const person2 = new Person("Bob", 25);
console.log(person2.name); // Output: Bob
console.log(person2.age);  // Output: 25

Output
Alice
30
Bob
25

Example 3: This example use class to create the object in JavaScript.

JavaScript
class emp {
    constructor(name, age) {
        this.name = name;
        this.age = age;

    }
}
const emp1 = new emp("Geek1", "25 years");
const emp2 = new emp("Beginner2", "32 years")
console.log(emp1.name + " : " + emp1.age);
console.log(emp2.name + " : " + emp2.age);

Output
Geek1 : 25 years
Beginner2 : 32 years

JavaScript Classes Use-Cases

Classes in JavaScript provide blueprints for creating objects with similar properties and methods. Objects are instances of classes. Classes encapsulate data and behavior, promoting code reusability and organization. Objects created from classes can have unique data but share the same methods defined in the class blueprint.

You can create a JavaScript class by using a predefined keyword named class before the class name.