JavaScript Classes

JavaScript classes are a type of function that allow for the creation of objects with defined properties and methods. Classes provide a way to organize and structure code, making it easier to reuse and extend.

Here is an example of a JavaScript class:

// define a class named "Person"
class Person {
  // define a constructor method to initialize the object
  constructor(name, age) {
    // set the object's name and age properties = name;
    this.age = age;

  // define a method named "greet"
  greet() {
    // log a greeting to the console
    console.log("Hello, my name is " + + " and I am " + this.age + " years old.");

In the above code, we are defining a class named “Person” that has a constructor method and a greet() method. The constructor method is used to initialize the object, setting its name and age properties. The greet() method logs a greeting to the console using the object’s name and age properties.

To use the Person class, we can create an instance of the class and call its methods:

// create an instance of the Person class
var person = new Person("John", 30);

// call the greet() method
person.greet(); // Hello, my name is John and I am 30 years old. 

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at

%d bloggers like this: