Demystifying JavaScript Classes

Demystifying JavaScript Classes

In this article, I will talk about classes. Classes are one of the interesting concepts in Javascript, but what exactly are classes?

They are the foundation of the object-oriented programming paradigm in Javascript. OOP promotes a structured approach to coding, allowing developers to model real-world entities as objects with properties and behaviors. Classes are a way to define objects or provide a blueprint for creating objects enabling code to be organized and structured in a more intuitive and logical manner

They help organize code by grouping related data and methods. By encapsulating properties and methods within a class, you can create a self-contained unit that represents a concept or entity. This enhances code readability, and maintainability, and makes it easier to understand and navigate the codebase, especially in larger projects

Classes promote the DRY principle (Don't Repeat Yourself) .i.e it promotes the reuse of code by providing a blueprint for creating multiple instances(objects) with the same properties and behavior

In the code snippet below, class Person defines a class called "Person" in JavaScript. The class body contains the properties, constructors, and methods associated with the Person class.

class Person{

//body

}

As we can see above

The class keyword is used to define a new class in JavaScript. Person is the name given to the class. You can choose any valid identifier as the class name. The class's body is the part in curly brackets{}, and it consists of the properties, constructor, and method

Class Instantiation

Instantiation means creating an object from a class. We need the keyword new and we call the name of the class after the word new.

Let us create a cat object from our Person class.

class Person {
  // code goes here
}
const person = new Person()
console.log(person)

Person {}

Class Constructor

The constructor is a special method that is called when creating an instance (object) of the person class. It is used to initialize the object's properties. In the given example, the constructor takes name and age as parameters and assigns them to the respective properties using the this keyword.

Whenever we instantiate we should pass the value of the properties. Let us pass a value at this time when we instantiate the class.

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

const person1 = new Person('Mariagoretti', 'Kimani')

console.log(person1)
Person {firstName: "Mariagoretti", lastName: "Kimani"}

Note that in Javascript, properties can be defined directly within the class body without being assigned a value.

In this example, an instance of the Person class is created using the new keyword. The constructor is called with the provided arguments.

Methods: The class can contain methods, which are functions associated with the class. The constructor inside a class is a built-in function that allows us to create a blueprint for the object. In a class, we can create class methods. Methods are JavaScript functions inside the class. Let us create some class methods.

class Person {
  constructor(firstName, lastName, age, country, city) {
    this.firstName = firstName
    this.lastName = lastName
    this.age = age
    this.country = country
    this.city = city
  }
  getFullName() {
    const fullName = this.firstName + ' ' + this.lastName
    return fullName
  }
}

const person1 = new Person('Maria', 'Kimani', 22, 'Kenya', 'Nairobi')
const person2 = new Person('Deo', 'Massawe', 32, 'Rwanda', 'Kigali')

console.log(person1.getFullName())
console.log(person2.getFullName())

Try this:

Create a class called PersonAccount. It has firstname, lastname, income, and expenses properties and it has total income, total expenses, accountInfo,addIncome, addExpense, and account balance methods. Incomes is a set of incomes and its description and expenses is also a set of expenses and its description

Principles of OOP

The following are the core concepts of OOP:

  • Encapsulation

    It involves bundling related data (properties and functions) together and restricting access to them from outside the object.

    It is like putting things in a box. It means that we keep related things together and hide them from the outside. Imagine you have a special toy box with many compartments. Each compartment holds a different toy. The toys are safe inside the box, and you can only play with them using the box's special openings. In programming, we use encapsulation to keep our code organized and protected. We group together related things like data and functions, and we control how they can be accessed and used from the outside.

  • Inheritance

    Inheritance is like passing on traits from parents to children. It means that some things can be shared or inherited between different objects or classes. Think about a family with different generations. Children can inherit certain characteristics from their parents, like eye color or hair type. In programming, we can create a "parent" class that has certain properties and behaviors. Then, we can create "child" classes that inherit those properties and behaviors. It helps us avoid repeating code and make our programs more organized

  • Polymorphism

    Polymorphism is like having many shapes or forms. It means that different objects can do similar things in their own unique ways.

    Imagine you have different animals, like a cat, a dog, and a bird. They all can make sounds, but each animal makes a different sound. In programming, we can have different classes with the same method names.

    Each class can have its own way of implementing those methods. It allows us to use different objects interchangeably, even if they have different behaviors

  • Abstraction

    Abstraction is like simplifying something complex. It means that we hide the complicated details and show only the important parts.

    Think about the remote control for your TV. You don't need to know how all the electronic parts inside the TV work. You only need to know how to press the buttons on the remote control to change channels or adjust the volume.

    In programming, we use abstraction to focus on the essential parts of our code and hide unnecessary complexity. It helps us understand and use things without worrying about all the technical details.

Best Practices and Tips

  • Follow naming conventions when defining classes, using capitalization and descriptive names (e.g., PascalCase for class names).

  • Organize class files and related code in a logical and modular structure, separating concerns and promoting maintainability.

  • Use proper documentation and comments to explain class functionalities and usage clearly.

  • Strive for the single responsibility principle, where each class should have a well-defined purpose and limited scope.

  • Favor composition over inheritance when designing class relationships, as it allows for more flexible and modular code.

Real-World Examples and Use Cases:

  • Classes in JavaScript are commonly used to model entities in real-world scenarios, such as users, products, or vehicles. For example, a user class can encapsulate user information like name, email, and password, along with methods for authentication and data manipulation.

  • Classes are utilized in building applications like e-commerce websites, where a Product class can represent products with properties like name, price, and description, along with methods for adding to a cart or calculating discounts.

  • Classes are also employed in game development to model game objects like players, enemies, or items, with properties and behaviors specific to each object type.

In conclusion, classes in JavaScript play a vital role in modeling real-world entities, building complex systems, and promoting code organization and reusability. They enable developers to create maintainable and scalable applications by encapsulating data and behavior.