Class syntax basics in JavaScript

August 1, 2020 - 3 min read

A class in JavaScript is a way of creating objects, The class acts as a blueprint for making objects out of it.

Class syntax is a new ES6 addition to JavaScript.

Before the class syntax, we used to create objects using the constructor functions.

Let's write a constructor function called User

// old way
function User(name, age) {
  this.name = name;
  this.age = age;
}

To create objects from the constructor function User() we have to use the new keyword followed by invoking the User() constructor function.

// old way using constructor function
function User(name, age) {
  this.name = name;
  this.age = age;
}

// create objects from User
const John = new User("John Doe", 23);

console.log(John); // {name: "John Doe", age: 23}

Let's rewrite the constructor function using the new class syntax.

To create a class we have to use the class keyword followed by the class name and curly braces {} like this,

// new way using class syntax
class User {

}

Class Syntax

Now we have defined a class. But how do we add methods, properties and get values to make the objects?

To get values for making the objects we have to use the constructor() method in the class.

// new way using class syntax
class User {
  // constructor function to
  // receive values for making objects
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

This constructor() method is the same as the one we used above using the constructor function.

The constructor method will be automatically called when using the new keyword.

Inside the constructor method, we have also defined the properties called name and age.

But how do we add methods?

We can add method to class like this,

// new way using class syntax
class User {
  // constructor function to
  // receive values for making objects
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  // adding a new method called sayName()
  // which returns the name property
  sayName() {
    return this.name;
  }
}

Lets now make an object from the class.

// new way using class syntax
class User {
  // constructor function to
  // receive values for making objects
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  // adding a new method called sayName()
  // which returns the name property
  sayName() {
    return this.name;
  }
}

// make new object John from class user
const John = new User("John Doe", 23);

console.log(John); // {name: "John Doe", age: 23}
console.log(John.age); // 23
console.log(John.sayName()); // John Doe

🚀 NOTE: A class must be called with the new keyword, otherwise it will throw an error.

We will be discussing more about classes in the next blog post

Feel free to share if you found this useful 😃.