JavaScript Classes - Modern JS
Tags: javascript, tutorial, oop, programming
Published: 2022-10-30 17:11:29

In this article, we will be learning about JavaScript Classes with examples.

## JavaScript Classes

JavaScript Classes are one of the features introduced in the ES6 version of JavaScript. JavaScript Classes are templates for creating JavaScript Objects.

Class is a blueprint of an object. It contains some details and based on these descriptions we can create as many objects as we want. 

You can think of a class as a prototype of a User. It contains all the details like name, age, salary, organization, etc based on which the User is created and the good part is that now we can re-use this class for creating multiple users or we can extend some other classes from this class.

---

## Defining Classes

JavaScript classes are similar to JavaScript constructor functions. For example,

**JavaScript Constructor Function:**

```js
// creating constructor function
function User()
{
    this.name = "John Carter";
    this.age = 29;
}

// creating object
const p1 = new User();
console.log(p1.name); // Output: John Carter
```

Whereas In JavaScript classes, we need to use the class keyword with the name of the class. For example,

**JavaScript Class:**

```js
// creating a class 'User'
class User
{
    constructor()
    {
        // initializing default values
        this.name = "John Carter";
        this.age = 29;
    }
}

// creating an object
const p1 = new User();
console.log(p1.name); // Output: John Carter
```

In the above example, we have created a JavaScript Class named User. `constructor()` method is a special method that executes every time an object (instance of a class) is created. So whenever our constructor is called `name` and `age `variables are initialized with default values.

The problem with the above example is that it is not reusable because our constructor method is not getting parameters. 

```js
// creating a class 'User'
class User
{
    constructor(userName, userAge)
    {
        // assigning values
        this.name = userName;
        this.age = userAge;
    }
}

// creating an object
const p1 = new User("John Carter", 29);
console.log(p1.name); // Output: John Carter
// creating an object
const p2 = new User("Mr. Bean", 35);
console.log(p2.name); // Output: Mr. Bean
```

Now we are passing parameters to the constructor method that gets assigned to the Class variables.

> Note: If you do not define a constructor method, JavaScript will add an empty constructor method.

---

## Creating Objects

To create a Class object we just need to call the class constructor. For example,

```js
// creating class
class User {...}

// creating an object
const p1 = new User("John Carter", 29);
console.log(p1.name); // Output: John Carter
```

If we don't want to pass values to the constructor() then we need to hardcode it in the constructor() method. For example,

```js
// creating a class 'User'
class User
{
    constructor()
    {
        // assigning values
        this.name = "John Carter";
        this.age = 29;
    }
}

// creating an object
const p1 = new User();
console.log(p1.name);
```

---

## Class Body

The body of a class is the part that is in curly brackets `{}`. This is where you define class members, such as methods or constructor.

### Constructor Method

The `constructor()` is a special method in a class that gets called automatically each time an object is created and it is used to initialize an object created with a class. There should be only one constructor method in a class. If we don’t define a constructor JavaScript will define an empty constructor.

There are two types of constructors: 

**1. Default constructor**
A default constructor does not get any parameters. For example,

```js
class User
{
    constructor()
    {
        this.name = "John Carter";
        this.age = 29;
    }
}
```


**2. Parameterized constructor**
A parameterized constructor gets parameters passed in. For example,

```js
class User
{
    constructor(userName, userAge)
    {
        this.name = userName;
        this.age = userAge;
    }
}
```

### Class Methods

It is very easy to create methods in JavaScript classes, you just need to give a name followed by `()`. For example,

```js
// creating a class 'User'
class User
{
    constructor(userName, userAge)
    {
        this.name = userName;
        this.age = userAge;
    }
    // defining a method
    greet()
    {
        return `Its your time ${this.name}`;
    }
}

// creating an object
const p1 = new User("Mr. Bean", 29);
// calling class method
console.log(p1.greet()); // Output: Its your time Mr. Bean
```

Here we have created a `greet()` method that returns a string value. We call a method by its name followed by `()`.

### Getters and Setters

In JavaScript, the getter method is used to get a value of an object, and the setter method is used to set a value of an object. The get keyword is used for getter methods and the set keyword is used for setter methods. For example,

```js
// creating a class 'User'
class User
{
    constructor(userName, userAge)
    {
        this.name = userName;
        this.age = userAge;
    }
    // getter method
    get userInfo()
    {
        return `${this.name} your age is ${this.age}`
    }
    // setter method
    set newAge(userAge)
    {
        this.age = userAge;
    }
}

// creating an object
const p1 = new User("John Carter", 29);

// calling getter method
console.log(p1.userInfo); // Output: John Carter your age is 29
// calling setter method
p1.newAge = 35;
console.log(p1.userInfo); // Output: John Carter your age is 35
```

Calling getter methods is simple we just need to give the name of the getter method and for calling a setter method we need to assign a value.

---

### Field Declarations

In JavaScript, classes can have public or private fields. Fields are nothing but variables that hold the information. 

**Public Field**
Public fields are helpful when we want to access/modify a particular field outside the class where it has been defined. By default all the properties of the class are public. For example,

```js
// creating a class 'User'
class User
{
    // public field
    salary = 0;
    
    constructor(userName, userAge)
    {
        this.name = userName;
        this.age = userAge;
        
    }
    bonus()
    {
        this.salary += 20;
        return `${this.name} you got bonus of $${this.salary}`;
    }
}

// creating an object
const p1 = new User("John Carter", 29);
console.log(p1.bonus()); // Output: John Carter you got bonus of $20
console.log(p1.salary); // Output: 20
```


**Private Field**
In order to declare a private class field, we need to use the # prefix. Private fields are helpful when we don’t want to allow read/write access to our fields outside the class. For example, 

```js
// creating a class 'User'
class User
{
    // private field
    #salary = 0;
    
    constructor(userName, userAge)
    {
        this.name = userName;
        this.age = userAge;
        
    }
    bonus()
    {
        this.#salary += 20;
        return `${this.name} you got bonus of $${this.#salary}`;
    }
}

// creating an object
const p1 = new User("John Carter", 29);
console.log(p1.bonus()); // Output: John Carter you got bonus of $20
console.log(p1.salary); // Output: undefined

```
---

## Hoisting

In JavaScript, we can not access a class before defining it, a class must be defined before using it, otherwise, it will throw a Reference Error. Unlike JavaScript functions and other declarations, the class is not hoisted. For example,

```js
// creating an object
const p1 = new User("John Carter", 29);
console.log(p1.name); // Output: ReferenceError: User is not defined

// defining a class
class User
{
    constructor(userName, userAge)
    {
        this.name = userName;
        this.age = userAge;
    }
}

```

---

## Wrapping up!

That's all for this article, hope you learned something. Thanks for reading, catch you later.

You can also buy me a coffee that would help me grow as an frontend developer :)

<a href="https://www.buymeacoffee.com/moazamdev" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 100px !important;" ></a>

---

{% user moazamdev %}