Classes in javascript

Published on: July 03, 2021 By T.Andrew Rayan

Classes are used to encapsulate the related data or objects and the code to work on those objects. It may contain functions, objects and variables that are encapsulated to form a class.

The class is identified with the class keyword.

Syntax for declaring a class:

Each class can have a constructor, which will be called when we create an object for the class.

Example for class declaration:

Here we have create a class named Employee and a constructor which gets name and age as parameter and assigns it to internal class variables name and age identified with this keyword. The this keyword denotes that the variable is the property of that class.

Now lets create a function in the class and work on the properties of the class.


Age is 30

In the above example, we have created a class with 2 properties, name and age which are initialized using constructor. Then we have 2 functions printName and printAge to print the name and age of the employee.

To create an object for the class we use the syntax

new className();

The className should be replaced with the desired class name. To supply values to name and age parameters through constructor we use

let employee = new Employee("Andrew",30);

We had assigned the created object to the variable employee. Now we can call the functions as well as the get the properties inside the class using the employee object.

Most Read