Classes in ES6

ES6 gave us the ability to create classes in Javascript without using prototypes. Class based components are commonly used in React as they allow state to be stored amongst other things.

class Car {
    // a constructor is a method which runs when the class is instantiated
    // constructors are used to define default properties a newly created object should have
    constructor(make, model, color) {
        this.make = make
        this.model = model
        this.color = color

    // to create a method, we define it in the class. 
    vroom() {
        console.log(`${this.model}'s go vrooooom`)

To instantiate a class:

let car1 = new Car("Nissan", "Pulsar", "Silver")


"Pulsar's go vrooooom"


Subclasses allow us to extend existing classes.

class ElectricCar extends Car {
    constructor(make, model, color, batterykWh) {
    // to inherit properties we need to use the super() function
    super(name, model, color); 
    this.batteryPower = batterykWh; 

    horsePowerHour() {
        return this.batteryPower * 1.3428

let car2 = new ElectricCar("Tesla","S","Black",81)


If you enjoyed this post consider sharing it on , , , or , and .