Edit Template
Edit Template

JavaScript Class

In JavaScript, a class is a structured way to define how objects should behave. It provides a reusable blueprint for creating multiple objects with similar properties and functions. Classes are part of Object-Oriented Programming (OOP) and are useful in organizing and scaling your code.

What Is a Class?

A class groups together data (properties) and functions (methods) into a single unit. This structure helps you create multiple objects that follow the same pattern without rewriting code.

Defining a Class

You can define a class using the class keyword. Inside the class, the constructor() method is used to initialize object properties:

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

				
			

The constructor runs automatically when a new object is created using the class.

Creating Objects from a Class

To create an object, use the new keyword followed by the class name:

				
					let person1 = new Person("Arshyan", 22);
let person2 = new Person("Ali", 18);

				
			

Now both objects have their own name and age values, but share the same structure.

Adding Methods to a Class

Classes can also contain methods—functions that belong to every object created from the class.

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

  greet() {
    return `Hello! I'm ${this.name}, and I'm ${this.age} years old.`;
  }
}

let p = new Person("Hamza", 28);
console.log(p.greet());

				
			

This will output:

				
					Hello! I'm Hamza, and I'm 28 years old.

				
			

Why Use Classes?

  • Repetitive work minimal – Create many objects from one definition.

  • Organized – Keep related properties and methods in one place.

  • Easier to manage – Especially in large projects.

Inheritance

JavaScript classes support inheritance, which allows one class to extend another and reuse its code. For example:

				
					class Student extends Person {
  constructor(name, age, grade) {
    super(name, age); // Call parent constructor
    this.grade = grade;
  }

  info() {
    return `${this.name} is in grade ${this.grade}.`;
  }
}

				
			

The Student class inherits from Person and adds a new grade property.

Key Points

  • Use class to define a blueprint for objects.

  • The constructor() sets up the initial values.

  • Add methods inside the class to define behavior.

  • Use new to create an object from the class.

  • Inheritance allows reuse and extension of class functionality.

Scroll to Top