How do classes work in JavaScript?


JavaScript classes, introduced in ECMAScript 2015 or ES 6, Classes are in fact “special functions”.
There are two ways to define a class in JavaScript using class keyword:-

  • Class Declaration
  • Class Expression

Class Declaration


The constructor method is a special method for creating and initializing an object created within a class. There can be only one special method with the name “constructor” in a class.

Default Constructor

If you do not specify a constructor method a default constructor is used.

Parameterized Constructor

Class Expression

Class expressions can be named or unnamed.

Class Hoisting

Class Declarations and Class Expression are not hoisted. You first need to declare your class and then access it.


Class Inheritance

The extends keyword is used in class declarations or class expressions to create a class that is a child of another class.
The extended keyword can be used to subclass custom classes as well as built-in objects.

Class Inheritance

  • Inherit Built-in Object

– Date
– String
– Array

class myDate extends Date {


Super ( ) is used to initialize parent class constructor. If there is a constructor present in a subclass,
it needs to first call super() before using “this”. A constructor can use the super keyword to call the
constructor of a parent class.

Method Overriding

Same function name with different implementation.

Parent ———————> show ( ) {return “Super Class”; }
Child ———————–> show ( ) {return “Sub Class”; } show ( ) {return “Super Class”; }

Static Method

The static keyword is used to define a static method for a class. Static methods are called without creating object and cannot be called through a class instance (object). Static methods are often used to create utility functions for an

Tagged : / / / /