πŸ“˜ JavaScript Classes β€” Introduction

βœ… What is a Class?

A class is a blueprint for creating objects. It bundles data (properties) and actions (methods) into one convenient structure.


πŸ“Œ Basic Class Syntax

jsCopyEditclass Person {
  constructor(name, age) {
    this.name = name; // Property
    this.age = age;   // Property
  }

  greet() {  // Method
    console.log(`Hello! My name is ${this.name} and I am ${this.age} years old.`);
  }
}

const person1 = new Person("Alice", 25); // Create new object
person1.greet(); // Hello! My name is Alice and I am 25 years old.

πŸ“Œ Key Points

  • class keyword declares a class.
  • constructor() is a special method to initialize new objects.
  • Methods inside the class define behaviors.
  • Use new keyword to create instances (objects) of the class.

πŸ“Œ Why Use Classes?

  • Cleaner syntax for creating objects.
  • Makes object-oriented programming (OOP) easier.
  • Supports inheritance and reuse of code.
  • Helps organize code in bigger projects.

πŸ§ͺ Try it Yourself!

jsCopyEditclass Animal {
  constructor(type) {
    this.type = type;
  }

  speak() {
    console.log(`This is a ${this.type}`);
  }
}

const dog = new Animal("dog");
dog.speak(); // This is a dog

🧠 Summary

TermMeaning
ClassBlueprint to create objects
ConstructorInitializes new object’s data
MethodFunction inside a class
InstanceAn object created from a class
new keywordCreates an instance of a class