Mastering Object-Oriented Programming in JavaScript
Published: 2023-04-26 08:29:18

Whether you’re new to JavaScript or you’ve been hacking at it for a while, you’ll definitely need to know about object-oriented programming. Object-oriented programming (OOP) is a programming paradigm that allows you to organize your code into self-contained, reusable, and modular components called "objects".

In this blog post, we'll cover the basics of object-oriented programming in JavaScript, including what objects are, how they are created, and how to use them to build complex applications. We'll also discuss the classes, and how to use inheritance and polymorphism to your advantage.

Without further ado, let’s dive right into it.
## Understanding Objects in JavaScript
To understand OOP, you have to first understand what an object is. In JavaScript, an object is a collection of key-value pairs where each key is a unique identifier or property, that points to a value. Objects in JavaScript are dynamic, which means properties can be added, modified, or removed at any time.

Let’s use me as an example. If we wanted to create an object with some of my details, here’s what it would look like.
```
let author = {
    name: 'Fimber',
    age: 26,
    height: '6.2ft'
}
```
In the above example, the object is “author”, while the key or properties are name, age, and height, while the values are Fimber, 26, and 6.2ft. While we created the object using the `“let”` keyword, you can also create it using `“const”` and `“var”`.

The properties of the object can be accessed by simply targeting it. For instance, if I wanted to get the name property from that object, I can simply `conslole.log` it like this 

```
console.log(author.name);
```

As I said earlier, you can also add properties to an object using either the dot notation or bracket notation, like this

```
author.country = 'Nigeria';
author['hobby'] = 'Writing';
```

The above would add a “country” and “hobby” property to the author object, and this can also be modified and removed at any time.

Now that we know what objects are, let’s dive a bit more into OOP in JavaScript.

## Defining Classes in JavaScript
Now that we know what objects are, it’s time to look at classes. Classes are a vital part of OOP, and it’s something you need to understand to fully master OOP. 

Classes are a way of creating reusable code templates for creating objects with similar properties and behaviors. Think of a class like a recipe for making cookies. The recipe tells you what ingredients you need and how to mix them together to make cookies.

In JavaScript, a class is like a recipe for making an object. It tells you what kinds of information, called properties, an object should have, and what things, called methods, the object should be able to do. So just like a recipe helps you make lots of cookies that are all the same, a class helps you make lots of objects that all have the same properties and methods.

Here’s an example of a class 

```
class Calendar {
  constructor(day, date) {
    this.day = day;
    this.date = date;
  }

  sayHello() {
    console.log(`Hello, today is ${this.day} and the date ${this.date}.`);
  }
}
```

As you can see, we've created a `“Calendar”` class with a constructor method that takes two parameters, day and date. We've also defined a `sayHello()` method that logs a message to the console using the values of day and date. With this, you can reuse that class several times over whenever you want. Pretty simple right? 

Well that’s exactly how classes work. Classes provide a powerful way to organize code and create reusable objects with their own properties and methods.

## Working with Inheritance and Polymorphism
Inheritance like the name suggests, is simply the process of borrowing parts of an older object to create a new project. It's like building a new toy car that has the same wheels as an old toy car, but a different body. Instead of building everything from scratch for the new toy, we can use some of the parts from the old toy and just change the parts we need to. It's a really neat trick that saves developers a lot of time in JavaScript.

Here’s an example.
```
class Person {
  constructor(name) {
    this.name = name;
  }

  shoot() {
    console.log(`${this.name} shoots a ball.`);
  }
}

class Player extends Person {
  shoot() {
    console.log(`${this.name} scores!.`);
  }
}

const player = new Player('Messi');
dog.speak(); // logs "Messi scores!."
```
In this example, we've created a class called `Person`, with a constructor method that takes a name parameter and a `shoot()` method. We've then created another class named `Player` that extends `Person` and overrides the first `shoot()` method to make the `Person` score instead of just shooting a ball.

Finally, we created an instance of the Player class and called its shoot() method, which logs "Messi scores." to the console. By overriding the Person class, the Player class basically borrowers the name constructor and then implements it in its own shoot() method through [Method Overriding](https://www.educba.com/overriding-in-javascript/#:~:text=Method%20Overriding%20is%20an%20OOPs%20concept%20closely%20knit%20with%20inheritance.%20When%20a%20child%20class%20method%20overrides%20the%20parent%20class%20method%20of%20the%20same%20name%2C%20parameters%20and%20return%20type%2C%20it%20is%20termed%20as%20method%20overriding.%20Also%2C%20be%20reminded%20that%20this%20is%20completely%20different%20from%20the%20concept%20of%20method%20overloading).

Polymorphism, on the other hand, refers to the ability of objects to take on different forms or behaviors depending on how they are used. 

In JavaScript, polymorphism is typically achieved through method overloading or method overriding. Method overloading means defining multiple methods with the same name but different parameters. When you call the method, the correct version of the method is called based on the parameters you pass in. Method overriding, on the other hand, means replacing a parent class method with a new implementation in a child class.

Think of Polymorphism as having a box with different shapes that can fit inside it. Let's say you have a circle shape, a square shape, and a star shape. Each shape is different, but they can all fit inside the box, even though they don't look the same. 

That's polymorphism in programming, where you have different objects that can do something in different ways, but they are all related in some way and can be used together. Just like how the circle, square, and star shapes can fit inside the same box. It's like having a bunch of toys that can all "play" in the same way, even though they're not exactly the same toy.

Here’s an example.
```
class Shape {
  area() {
    console.log('Shape area undefined');
  }
}

class Square extends Shape {
  constructor(side) {
    super();
    this.side = side;
  }

  area() {
    console.log(`Square area: ${this.side * this.side}`);
  }
}

class Circle extends Shape {
  constructor(radius) {
    super();
    this.radius = radius;
  }

  area() {
    console.log(`Circle area: ${Math.PI * this.radius * this.radius}`);
  }
}

const square = new Square(5);
const circle = new Circle(3);

const shapes = [square, circle];

shapes.forEach(shape => {
  shape.area();
});
```
As you can see in the above example, we've defined a Shape class with an `area()` method that logs a message to the console. We've then created two child classes, `Square` and `Circle`, that override the `area()` method to calculate and log the area of the respective shapes. We've also created instances of both classes and added them to a new array. 

Finally, we've looped over the array and called the `area()` method on each object, which logs the correct area message for each shape. This perfectly demonstrates polymorphism, as we are using objects of different classes interchangeably based on their common interface of having an `area()` method. If you’d like to read more about Polymorphism, [this fantastic article](https://www.geeksforgeeks.org/polymorphism-in-javascript/) targets it in depth.

## Conclusion
If you made it this far, then by now you can rest assured that you now have a solid idea of what object-oriented programming is in JavaScript. Mastering object-oriented programming in JavaScript can be a game-changer for developers looking to write more efficient, modular, and maintainable code. 

By understanding the key concepts of OOP, such as classes, inheritance, encapsulation, and polymorphism, developers can create powerful and flexible software objects that can be reused and extended in various contexts. 

I hope this article has been a great help to you. Till next time, live a life of value.