Getting Started with JavaScript Classes
Tags: javascript, webdev, 100daysofcode
Published: 2021-09-05 10:06:59

Hey All 👋 , with this article I'm going to start a series of articles on JavaScript concepts. So I'm starting off this series with an article on JavaScript Classes. In this article, I'm going to cover all you need to get started with JS classes.

---

**Table Of Contents -**
* Basics of JS Classes
* getters and setters
* static methods
* inheritance and extends
* polymorphism

---

## Basics of JS Classes

> " In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods). " - Wikipedia

In simpler words, Classes are the blueprints used to create objects.

**Note:** JavaScript objects are entities having **properties** and **methods**.

Let's understand Classes with the help of this example - 

![Classes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kgizbuwgd49qb4yvlbb6.png)

Classes are like templates. We can see that we have one Car class having a property color in the picture, but we have not specified which color.

With the help of this class, we can create different objects with specific colors, like if we pass red as a color parameter, then a red car is created( i.e., object with red color property).

**What can we define with a Class definition? -**

We can define two main areas with the help of a class definition -
* **Instance Properties -**
		> What an object will have.
		Example - name, color, etc.


* **Instance Methods -**
		> What an object will do.
		Example - add, area, etc. ( any function )

**Note:** An instance is a specific representation of an object, or we can say an instance is an object created using a particular class.

### Class syntax -

Let's look at the code first then we'll talk about its parts one by one -

```javascript

class Person {
    constructor(personName) {
        this.name = personName; 
    } 
    sayHi() {
        console.log(`Hi ${this.name}`); 
    }
}
// Usage:
let person1 = new Person("Alok"); 
person1.sayHi(); //Output - Hi Alok

```

We have to use the **class keyword** to create a class, followed by a **class name** that conventionally starts with a capital letter, i.e., Person in the above code.

The class definition goes between **two curly braces {}**.

Every class has a **constructor**, and a constructor is basically a method that runs only once during the object's life, specifically when the object is being created.

The constructor is used to setup the object, i.e., to define the states of the object ( properties ).

> In **this.name = personName** -

**this** refers to the current object which is being created.

**name** refers to the property name.

**personName** is the argument passed while creating the object.

also, **sayHi()** is a method with some functionality.

**Let's see how we create an object using a class -**

We create an object using the **new keyword** with a class as in this code, we have created a **person1** object using the Person class.

Also, we have passed **"Alok"** as an argument to the constructor method while creating the object.

We have called the **sayHi()** method using **person1.sayHi()**, which runs the code inside the method and gives output **Hi Alok**.

Let’s see one more example - 

```javascript

class Rectangle {
  constructor(length, breadth) {
    this.length = length;
    this.breadth = breadth;
  }
 
  area() {
    return this.length * this.breadth;
  }
}
 
let rectangle1 = new Rectangle(4, 5);
rectangle1.area(); // gives Output: 20

```

In this example, we have created a **rectangle1** object with arguments **4** and **5**.

**area()** method uses these arguments stored in properties to find the area( length*breadth ) and return it.

---

## getters and setters

Getters and Setters are basically used to define methods in a class and then used as if they are properties.

Let's understand these with an example -

```javascript

class Square {
  constructor(side) {
    this.side = side;
  }
 
  get area() {
    return this.side * this.side;
  }
 
  set area(area) {
    this.side = Math.sqrt(area);
  }
}
 
let square1 = new Square(4);
console.log(square1.area); // gives output: 16
square1.area = 25;
console.log(square1.side); // gives output: 5

```

To use a getter, we have to use the **get** keyword and then define the method, and we can call it as a property ( **square1.area** -  notice we don't have () while calling the area method ).

While to use a setter, we use the **set** keyword and then define the method, and we call it by directly assigning the argument to it as we do in a property ( **square1.area = 25** - notice we don't pass the argument here; instead assign it directly ).

---

## static methods

Static methods are defined in the class but are not used by or part of the created object.

Or, in simple words, static methods don't require an instance of a class to be created in order to be used.

Static methods are also called helper methods.

Let's understand this with an example -

```javascript

class Temp {
  constructor() {
  }
 
  static isEqual(a, b) {
    return a === b;
  }
}
 
Temp.isEqual(4,5); // returns false
Temp.isEqual(4,4); // returns true

```

A static method is defined using a static keyword followed by a method definition ( i.e. **static isEqual()** ).

A static method can be called directly using the class name ( i.e. **Temp.isEqual()** ).

As you can see above, we don't need to create an object to use the static method.

Also, we can pass objects while calling a static method.

Let's see an example -

```javascript

class Temp {
  constructor(value) {
    this.value = value;
  }
 
  static isEquals(Obj1, Obj2) {
    return Obj1.value === Obj2.value;
  }
}
 
let temp1 = new Temp(4);
let temp2 = new Temp(6);
let temp3 = new Temp(4);
 
Temp.isEquals(temp1,temp2); // returns false
Temp.isEquals(temp1,temp3); // returns true

```

Here you can see we have passed **objects as arguments** to a static method, which is called directly using the class name.

Then the method accesses each value property using **objectName.value** and returns the result.

---

## inheritance and extends

With the help of inheritance, a class can extend another class. Or, in simpler words, one class can have access to methods of another class and also have its own methods.

Let's understand this with the help of this picture -

![inheritance and extends](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1cj7xlbcgnlkkz33tarp.png)

In the above picture, a Child class extends a Parent class. As we can see, the Child class has access to the methods of the Parent class ( i.e., add() and multiply() ); also, it has its own methods( i.e., divide() and area() ).


Let's understand inheritance with the help of an example.

Have a look at the code first then we'll talk about its parts one by one -

```javascript

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
 
  sayHi() {
    console.log(`Hi!!! this is ${this.name} and I'm ${this.age} years old.`);
  }
}
 
class Programmer extends Person {
  constructor(name, age, role) {
    super(name, age);
    this.role = role;
  }
 
  info() {
    this.sayHi();
    console.log(`And I'm a ${this.role}`);
  }
}
 
let person1 = new Person("Aman", 20);
let programmer1 = new Programmer("Alok", 21,
 "Web Developer");

```

Here we have a **Person** class that has a constructor taking arguments - **name** and **age**. Also, it has a method named **sayHi()** which basically **console.log** out "Hi!!! this is **name** and I'm **age** years old. ( name and age are arguments passed while creating an object ).

Next, we have another class named **Programmer**. And a class can inherit another class using **extend keyword** followed by the class name to be inherited. As here, the **Programmer class extends Person Class**.

The programmer class has a constructor taking arguments **name**, **age**, and **role**. The **super keyword** is used to call the constructor of the Person class. And now it has the Person class properties and also its own property - **role**.

The Programmer class has a method **info()** which calls the Person class method - **sayHi()** ( as now the Programmer class can access the Person class ). And also, **console.log** out "And I'm a **role**" ( role is an argument passed while creating an object ).

We have also created two objects **person1** and **programmer1**, one each of the Person and Programmer Class. 

Now let's have a look at different operations on them and their results -

* ![example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/es3knzjtycgfgra9ehbw.png)

Here you can see the programmer1 object has properties of Person class - **name** and **age**. Also, it’s own property - **role**.

* ![example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dptrybtx3zbbg9r4zo71.png)

Here we have called the **sayHi()** method using the object of the Person class.

* ![example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rqpe3p105feacemax2t9.png)

Here we have called the **info()** method using the object of the Programmer class, and you can see it called and executed the **sayHi()** method of the Person class with arguments passed while creating the programmer1 object; also, it executed its own console.log out.

* ![example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n5mnyh747rydgjdetxti.png)

Here you can see we have called the **sayHi()** method of the Person class using the object of the Programmer Class ( as the Programmer class extends the Person class and has access to its methods ). Also, it takes arguments passed while creating progammer1 as we have called the **sayHi()** method using the object of the Programmer class.

* ![example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hzo325jc4nsf37sveszj.png)

But we can't access the method of the Programmer class using the object of the Person class as the Parent class doesn't have access to the Child class.

---

##  polymorphism

Polymorphism allows us to override the method of the Parent Class.

Let's understand it with the help of an example - 

```javascript

class Animal {
  constructor(name) {
    this.name = name;
  }
 
  sayName() {
    console.log(`${this.name} is an Animal.`);
  }
}
 
class Dogs extends Animal {
  constructor(name) {
    super(name);
  }
 
  sayName() {
    console.log(`${this.name} is a Dog.`);
  }
}
 
let animal1 = new Animal("Tiger");
let dog1 = new Dogs("Bull Dog");

```

Here both the Parent Class ( Animal ) and the Child Class ( Dog ) have the same method **sayName()**. 

And we have seen earlier that we can call a Parent class method using an object of a Child class, but in this case, both the methods have the same name.

Let's see what happens when we call them - 

* ![example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/85cem60iz3t2fsklrcdy.png)

It works fine as it should; now, let's see what happens when we call the **sayName()** method using **dog1** object -

* ![example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u0earnfihwfhfgpqj4sd.png)

Here you can see the sayName() method of the Dog class overrides the sayName() method of Animal Class.

And this is how Polymorphism allows overriding the Parent class method.

---

I have tried to keep it simple and precise, thanks for reading it till last, and also I have a lot planned for the future So stay tuned 🙂

If you find this useful then you can share it with others :)

Feel free to drop a [Hi and let's chat 👋👋👋](twitter.com/thecoollearner)

---

Read the next blog in the series 
&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;[Getting Started with JavaScript Modules 👉](https://dev.to/thecoollearner/getting-started-with-javascript-modules-2mkg)