Modern JavaScript
About Lesson

In this JavaScript lesson we are going to talk about JavaScript Classes. so in ES6 the keyword class was introduced,  a class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class.

 

 

In the past we can do like this.

 

 

 

Now let’s convert our example with ES6 classes.

 

 

 

Let’s add functions in our class.

 

 

JavaScript Classes Features

As we already mentioned that Classes are feature in JavaScript that provide a way to define and create objects using a class based syntax. these are some features of JavaScript classes along with code examples:

 

  1. Class Declaration: You can define a class using the class keyword followed by the class name.

In this example, the Person class is defined with constructor and sayHello method. An instance of the Person class is created and the sayHello method is called.

 

 

  1. Inheritance: You can create subclass that inherits from a parent class using the extends keyword.

In this example Animal class is defined with constructor and speak method. Dog class is defined as subclass of Animal and overrides the speak method to make the dog bark.

 

 

  1. Static Methods: You can define static methods on class using the static keyword. Static methods can be called on the class itself rather than on an instance of the class.

In this example, the MathUtils class is defined with static methods square and cube. static methods can be called on the class itself to perform mathematical operations.

 

In conclusion we can say that classes in JavaScript provide powerful and flexible way to create objects and perform object oriented programming. They are easy to read and can help make your code more organized and maintainable.