JavaScript Classes

In JavaScript, classes are the special type of functions. We can define the class just like function declarations and function expressions.

The JavaScript class contains various class members within a body including methods or constructor. The class is executed in strict mode. So, the code containing the silent error or mistake throws an error.

The class syntax contains two components:

  • Class declarations
  • Class expressions

Class Declarations

A class can be defined by using a class declaration. A class keyword is used to declare a class with any particular name. According to JavaScript naming conventions, the name of the class always starts with an uppercase letter.

Class Declarations Example

Let's see a simple example of declaring the class.

Test it Now

Output:

101 Martin Roy
102 Duke William

Class Declarations Example: Hoisting

Unlike function declaration, the class declaration is not a part of JavaScript hoisting. So, it is required to declare the class before invoking it.

Let's see an example.

Test it Now

Output:

JavaScript OOPs Classes

Class Declarations Example: Re-declaring Class

A class can be declared once only. If we try to declare class more than one time, it throws an error.

Let's see an example.

Test it Now

Output:

JavaScript OOPs Classes

Class expressions

Another way to define a class is by using a class expression. Here, it is not mandatory to assign the name of the class. So, the class expression can be named or unnamed. The class expression allows us to fetch the class name. However, this will not be possible with class declaration.

Unnamed Class Expression

The class can be expressed without assigning any name to it.

Let's see an example.

Test it Now

Output:

emp

Class Expression Example: Re-declaring Class

Unlike class declaration, the class expression allows us to re-declare the same class. So, if we try to declare the class more than one time, it throws an error.

Test it Now

Output:

101 Martin Roy
102 Duke William
103 James Bella
104 Nick Johnson

Named Class Expression Example

We can express the class with the particular name. Here, the scope of the class name is up to the class body. The class is retrieved using class.name property.

Test it Now

Output:

Employee
Next TopicJS Object




Contact US

Email:[email protected]

JS Class
10/30