Loading
Class in JavaScript-tutorial
In JavaScript, a class is a blueprint for creating objects that share the same properties and methods.
Classes were introduced in ECMAScript 6 (ES6) to provide a cleaner, more structured way to work with objects and inheritance.

A JavaScript class can be created using

  • Class Declarations
  • Class Expressions



What is a Class Declaration ?

To declare a class in JavaScript, use the class keyword followed by the class name.

By convention, class names should start with an uppercase letter.



Example:

<!DOCTYPE html>
<html>

<body>

    <script>
        // Declaring class
        class Employee {
            // Constructor to initialize properties
            constructor(id, name) {
                this.id = id;
                this.name = name;
            }

            // Declaring method
            detail() {
                document.writeln(this.id + " " + this.name + "<br>");
            }
        }

        // Creating objects
        var e1 = new Employee(101, "Martin");
        var e2 = new Employee(102, "Duke");

        // Calling method
        e1.detail();
        e2.detail();
    </script>

</body>

</html>

Output

Uploaded Image




What is a Class Expression ?

A class expression is another way to define a class.


Class expressions can be

  • Unnamed
  • Named



Unnamed Class Expression

Class is assigned to a variable without giving it a class name.



Example:

<!DOCTYPE html>
<html>

<body>

    <script>
        var emp = class {
            constructor(id, name) {
                this.id = id;
                this.name = name;
            }
        };
        document.writeln(emp.name); // Output: emp
    </script>

</body>

</html>

Output

Uploaded Image




Named Class Expression

Class expression includes a name.

The class name is local to the class body and not accessible outside.



Example:

<!DOCTYPE html>
<html>

<body>

    <script>
        var emp = class Employee {
            constructor(id, name) {
                this.id = id;
                this.name = name;
            }
        };
        document.writeln(emp.name); // Output: Employee

        // document.writeln(Employee.name);
        // This would throw: ReferenceError: Employee is not defined
    </script>

</body>

</html>

Output

Uploaded Image




Key Point

  • Classes make JavaScript code more organized and easier to read.
  • Use the constructor() method to initialize object properties.
  • Methods defined inside a class are shared among all instances.
  • Classes can be declared (using class) or expressed (as expressions, named or unnamed).