what is a class in javascript

In JavaScript, a class is a way to define a custom type with its own properties and methods. It is a template for creating objects that encapsulate data and related behavior. You can create a class using the class keyword, followed by the name of the class.

Here is an example:

index.tsx
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  sayHello() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
  }
}

let person1 = new Person("Alice", 25);
person1.sayHello(); // output: Hello, my name is Alice and I'm 25 years old.
311 chars
14 lines

In this example, we define a Person class with a constructor that takes a name and an age parameter. We also define a sayHello method that logs a message to the console. We then create a person1 object of type Person and call its sayHello method.

gistlibby LogSnag