JavaScript Classes - Modern JS

moazamdev

Moazam Ali

Posted on October 30, 2022

JavaScript Classes - Modern JS

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:

// 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
Enter fullscreen mode Exit fullscreen mode

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

JavaScript Class:

// 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
Enter fullscreen mode Exit fullscreen mode

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 agevariables 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.

// 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
Enter fullscreen mode Exit fullscreen mode

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,

// creating class
class User {...}

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

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

// 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);
Enter fullscreen mode Exit fullscreen mode

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,

class User
{
    constructor()
    {
        this.name = "John Carter";
        this.age = 29;
    }
}
Enter fullscreen mode Exit fullscreen mode

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

class User
{
    constructor(userName, userAge)
    {
        this.name = userName;
        this.age = userAge;
    }
}
Enter fullscreen mode Exit fullscreen mode

Class Methods

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

// 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
Enter fullscreen mode Exit fullscreen mode

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,

// 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
Enter fullscreen mode Exit fullscreen mode

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,

// 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
Enter fullscreen mode Exit fullscreen mode

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,

// 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

Enter fullscreen mode Exit fullscreen mode

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,

// 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;
    }
}

Enter fullscreen mode Exit fullscreen mode

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 :)

Buy Me A Coffee


💖 💪 🙅 🚩
moazamdev
Moazam Ali

Posted on October 30, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

JavaScript Classes - Modern JS
javascript JavaScript Classes - Modern JS

October 30, 2022