Skip to main content

Command Palette

Search for a command to run...

Getting Into Javascript Classes: A Practical Guide

Updated
•6 min read•View as Markdown
Getting Into Javascript Classes: A Practical Guide
T

Build && Write === true

Object Oriented Programming is a powerful model that has become increasingly popular and essential in software development. JavaScript is object-oriented, meaning it supports the principles of OOP. In simple terms, classes are templates used to build objects. OOP deals mainly with objects with all data embedded within the object. In this article, we will be going over important aspects of classes with practical examples and get to build a wallet prototype that outputs on the browser’s console.

Why is OOP Important?

Object Oriented Programming is crucial and popular in software development for several reasons:

Readability: Codes written in OOP are easy to read, understand, and grasp the functionality.

Maintainability: Due to the relatable form of writing OOP objects, it is easier to maintain operations like updates.

Encapsulation: This prevents the internal mode of the classes from unnecessary access.

Organization: Codes are organized into modules, which gives it a much better structure and aids in locating important aspects of the program.

Prerequisite

To get a full grasp of this article, you should have basic knowledge of JavaScript.

What are Classes?

As earlier defined, classes are templates used to create objects. Classes are made of properties that are defined in the constructor function embedded within the class. For example, a Person class has a first name, last name, age, etc. These are the properties that define the person object.

class Person{
    constructor(firstName,lastName,age){
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age
    }
}

The above example is a class of Person, with defined properties of firstName, lastName and age in the constructor function. In order to have access to the Person class, we need to create an object from Person using the new keyword.

const person = new Person ('John', 'Doe', 23)

We have now created a person object from the Person class as a new instance. After the new keyword and class name, the properties defined in the constructor function are passed. To have access to the properties individually, we use the dot notation on the person object.

console.log(person.firstName) //Output: 'John'
console.log(person.lastName) //Output:'Doe'
console.log(person) //output: Person {firstName: 'John', lastName: 'Doe', age: 23}

In the last line of the example above, logging the person object will output the Person class with the properties and values passed in alongside.

To check the data type of person, we can use the typeof method.

console.log(typeof person) //Output: Object

Getters and Setters

These methods are known as Properties accessors. Getter methods are used to retrieve the value of a class property. It is always prefixed with the get keyword. Using our Person class, we will add a getter for firstName and lastName called fullName.

class Person{
    constructor(firstName,lastName,age){
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age
    }

    get fullName(){
        console.log(`${this.firstName} ${this.lastName}`)
    }
}
const person = new Person('John', 'Doe')
person.fullName  //Output: John Doe

The get method fullName, has access to the Person class properties and retrieves the required properties values.

Setter methods on the other hand, is used to update the value of the property. For instance, we want to change the firstName property to Jane. We used the set method in the Person class.

class Person{
    constructor(firstName,lastName,age){
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age
    }
    set changeFirstName(firstName){
        this.firstName = firstName;
}

In the above example, we have a set method called changeFirstName that takes in a parameter of firstName.

NOTE: I used the same name for the getter and setter to let you understand that the get / set keyword in front does the magic. Also, setters takes a value that is later assigned to a property. Now, we are ready to change the firstName from John to Jane.

const person = new Person ('John', 'Doe', 23)
person.changeFirstName = 'Jane'
console.log(person) //output: Person {firstName: 'Jane', lastName: 'Doe', age: 23}

You can see that the firstName property has been updated to Jane and stored in the Person object.

Inheritance

This is a fundamental part of OOP which allows a class (subclass or derived) to inherit the properties and methods from a different class mostly the super or base class. This is achieved using the extends keyword.

class Person{
    constructor(firstName,lastName,age){
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age
    }
class Student extends Person{
    constructor(firstName,lastName,schoolName){
        super(firstName,lastName)
        this.schoolName = schoolName
    }

    profileCard(){
        console.log(`${this.firstName} ${this.lastName} schooling in ${this.schoolName}`)
    }
}

In the above example, we have a new class of Student that is inheriting firstName and lastName from the Person super class. However, we want to add another property of schoolName to it.

The super part houses the derived constructor from the super class and initialize the schoolName property.

The profileCard method will consist of the inherited properties and newly defined property of schoolName.

const student = new Student ('Jane', 'Doe', 'High School')
student.profileCard() //Output: Jane Doe schooling in High School

Having known enough of how Object Oriented Programming using Classes works in JavaScript, we will do a simple fun console wallet for you to grasp some of these concepts better.

Building a Console Wallet

Quick Overview

This project is basically a calculating application that involves high-order array operations, arithmetic and of course, embeds the principles of OOP.

In this fun project, we will be creating a Wallet class with an initial balance of 0, deposits and withdrawals set to an empty array. I will be using the ' _' convention for my private class properties.

class Wallet{
    constructor(){
        this._balance = 0;
        this._deposits = [];
        this._withdrawals = [];
    }
}

The idea here is to add methods that takes in an amount, pushes it into either of the arrays and does the computations and finally, updates the _balance.

Deposits(amount){
    this._deposits.push(amount);
    this._balance += this.amount
}
Withdrawals(amount){
    this._withdrawals.push(amount);
    this._balance -= this.amount
}

The Deposits method takes in an amount value which would always be pushed into the _deposits array. Then, the _balance updated by adding the amount to the previous value of balance. Line 3 simply means this._balance = this._balance + this.amount.

Same process happens in the Withdrawals method but the computation is subtracting the amount from the _balance.

Computations

With the this._deposits array containing amounts, we will like to knowing the total deposit values in order to subtract from the this._withdrawals array to get the current balance of the wallet. We can achieve this by using the reduce function on both arrays.

Computing Total Deposits

totalDeposits(){
        return this._deposits.reduce((accumulator,currentValue)=> accumulator + currentValue,0)
    }

This method, totalDeposits will return the value of the reduce function on this._deposits array. The reduce function takes the accumulator as the previous value and the currentValue as the present value that will be added to give the accumulator a new value, this is called iteration. The operation that will be performed will be adding both variables and the 0 is the set initial value of the accumulator.

Computing Total Withdrawals

totalWithdrawals(){
        return this._withdrawals.reduce((accumulator,curentValue)=>accumulator + curentValue,0)
    }

Same process occurs here but on the this._withdrawals array.

Computing Balance

Now we have our totalDeposits and totalWithdrawals methods, we can create another method that gets the difference between the total of both arrays and output as the balance.

balance(){
        const totalDeposit = this.totalDeposits()
        const totalWithdrawal = this.totalWithdrawals()
        const diff = totalDeposit - totalWithdrawal
        this._balance = diff
        return diff
    }

We set this._balance to the value of diff and it serves as the current balance value.

Now, we can create an object from the Wallet class and apply all the methods.

const wallet = new Wallet()
wallet.Deposits(500)
wallet.Withdrawals(200)
console.log(wallet._deposits)    //Ouput: [500]
console.log(wallet._withdrawals)    //Ouput: [200]
console.log(wallet.balance())        //Output: 300

Our console wallet is working just as we expected. More amounts can be added via the methods or pushing directly using the wallet._deposits.push(amount). Total deposits and withdrawals can also be displayed.

console.log('Total deposits is:',wallet.totalDeposits())
console.log('Total withdrawals is:',wallet.totalWithdrawals())

Moving forward

JavaScript gives us the option of manipulating the DOM, this pet project can be taken a step further in that regards to create a more interactive and dynamic application. Here is a GitHub link to my Calories Tracker class-based project.

C

With this OOP insight , this can help me grow on other programming I'm in to. Thanks_teetech🥰

1
T

Glad you found it helpful

1