In today's overview of ES6 let's have a look at classes. Classes essentially is just a syntactical sugar over the existing JavaScript's prototype-based inheritance. As MDN clearly states, the class syntax does not introduce a new object-oriented inheritance model to JavaScript. Nevertheless, it's a nice addition which I use often.

Prototypal inheritance

Before ES6, the primary way of doing object-oriented programming was via prototypal inheritance and explicitly declaring methods on object's prototype.

Let's have a quick look at the ridiculousness of how it works in practice. See in the example below how toyota inherits Car prototype and in return can use its methods and properties. The amount of boilerplate code that getting that to work requires is appaling.

Classes

ES6 classes under the hood do the same thing as the code in the previous example but is a lot more readable and intuitive to understand. Let's take a look at how we can use ES6 classes to refactor the previous example.

Note the usage of Class keyword to declare a class. Also, see how we have a constructor method which works similarly to traditional object-oriented languages such as Java. To extend another class we just have to use extends keyword i.e. class Toyota extends Car and pass the options to the parent class via super() method. That's all there is to it. Pretty great, huh?

When to use ES6 classes?

There is no reason not to use ES6 classes so I would recommend using them whenever prototypal inheritance is needed. But rather than using the old obscure syntax and make life difficult for no reason just take advantage of syntactic sugar provided by ES6 classes. Happy usage!