0
0
Javascriptprogramming~5 mins

Class syntax in Javascript

Choose your learning style9 modes available
Introduction

Classes help you create blueprints for objects. They make it easy to organize and reuse code for things that share the same features.

When you want to create many similar objects, like multiple users or cars.
When you want to group related data and functions together.
When you want to make your code easier to read and maintain.
When you want to use inheritance to create new objects based on existing ones.
Syntax
Javascript
class ClassName {
  constructor(parameters) {
    // initialize properties
  }

  methodName() {
    // method code
  }
}

The constructor is a special method that runs when you create a new object.

Methods inside the class define actions the objects can do.

Examples
This class creates a person with a name and age, and a method to say hello.
Javascript
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
}
This class creates a car with make and model, and a method to show its details.
Javascript
class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }

  display() {
    console.log(`Car: ${this.make} ${this.model}`);
  }
}
Sample Program

This program defines an Animal class with a name and a speak method. It creates a dog object and calls speak.

Javascript
class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

const dog = new Animal('Dog');
dog.speak();
OutputSuccess
Important Notes

Use this to refer to the current object inside methods.

Class names usually start with a capital letter to show they are blueprints.

You can create many objects from one class using the new keyword.

Summary

Classes are blueprints for creating objects with shared properties and methods.

The constructor sets up new objects when created.

Use methods inside classes to define what objects can do.