DEV Community

Cover image for Object Oriented Programming in JavaScript.
Birusha Ndegeya
Birusha Ndegeya

Posted on • Updated on

Object Oriented Programming in JavaScript.

Understanding the basics of object-oriented programming (OOP) in JavaScript is crucial for software developers, especially those focused on front-end web development. Before diving into that, allow me to introduce myself. Hi 👋!, I'm Birusha Ndegeya. I was born in Goma, DR Congo, and I'm incredibly passionate about software development.

Completing this tutorial will enable you to grasp the four fundamental pillars of object-oriented programming:

✅ Encapsulation,
✅ Inheritance,
✅ Polymorphism, &
✅ Abstraction.

Understanding these concepts is crucial for becoming proficient in object-oriented programming, as they provide the building blocks for designing and implementing robust, maintainable, and scalable software solutions.

If you'd like to follow along with this tutorial, let's start by organizing our file structure and creating the necessary files: index.html, index.css, and index.js. Here's how you can set it up:

Create a folder for your project:

object-oriented-programming-basic

│   index.html
│   index.css
│   index.js

Enter fullscreen mode Exit fullscreen mode

index.html: This will be your HTML file where you'll include references to your CSS and JavaScript files.

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Object-Oriented Programming Tutorial</title>
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <h1>Object-Oriented Programming Tutorial</h1>
    <!-- Content goes here -->
    <script src="index.js"></script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

index.css: This will be your CSS file where you can style your HTML elements.

html,
body {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: sans-serif;
}

Enter fullscreen mode Exit fullscreen mode

index.js: This will be your JavaScript file where you'll write your code for the tutorial.

console.log("Hello World");
Enter fullscreen mode Exit fullscreen mode

Retrieve starter code from GitHub:
If you have starter code on your GitHub, you can clone the repository or download the files and place them accordingly in your project folder.

With this organization, you have separate files for HTML, CSS, and JavaScript, which helps maintain a clean and modular structure for your project. You can now start coding along with the tutorial, implementing the concepts of object-oriented programming in JavaScript within the index.js file and styling your HTML elements using the index.css file.

With object-oriented programming, we aim to express entities that are not inherently defined in JavaScript. While JavaScript provides native types like strings, numbers, and objects, it lacks built-in constructs for representing real-world entities such as a person, an animal, or an airplane. Object-oriented programming bridges this gap by allowing us to define custom types or classes to represent these entities.

When creating a class, it's essential to start with the keyword class, and the naming convention should follow PascalCase, where the first letter is uppercase. This convention helps distinguish classes from variables and functions, enhancing code readability and maintainability.

class Person {
}
console.log(Person) // output [Class Person]
Enter fullscreen mode Exit fullscreen mode

To begin utilizing the class, we must instantiate an instance of it.

class Person {

}

const comedian = new Person();
const musician = new Person();
console.log(comedian); // Person {}
console.log(musician); // Person {}
Enter fullscreen mode Exit fullscreen mode

Now, we can assign properties to each person as values held by a person once created.

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

const comedian = new Person();
const musician = new Person();
console.log(comedian); // Person { name: undefined, age: undefined}
console.log(musician); // Person { name: undefined, age: undefined}

Enter fullscreen mode Exit fullscreen mode

Then, you'll notice that the output is currently undefined. Now, we'll proceed to instantiate instances with specific values assigned.


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

const comedian = new Person("Birusha", 20);
const musician = new Person("Jill", 18);
console.log(comedian); // output Person { name: "Birusha", age: 20} 
console.log(musician); // output Person { name: "Jill", age: 18 }

Enter fullscreen mode Exit fullscreen mode

A method is a function or the ability, such as a person having properties like name "Jill" and being able to perform actions like "go right" or "speak Swahili".

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

   greet () {
      return `Hello my name is ${this.name} and I have ${this.age}`
   }
}

const comedian = new Person("Birusha", 20);
const musician = new Person("Jill", 18);
console.log(comedian.greet()); // output: "Hello my name is Birusha and I have 20"
console.log(musician.greet()); // output: "Hello my name is Jill and I have 20"

Enter fullscreen mode Exit fullscreen mode

1st core Fundamental | ENCAPSULATION

Encapsulation in object-oriented programming is like packaging data and the methods that operate on that data into a single unit, which we call an object. This encapsulated unit hides the internal state of the object, exposing only the necessary functionality to interact with it.


class Fruit {
   constructor(color, name) {
      this.color = color;
      this.name = name;
   }

   description () {
      return `${this.name} is ${this.color}`;
   }
}

const apple = new Fruit("red", 'apple');
const banana = new Fruit('yellow', "banana");

console.log(apple.description()); // apple is red
console.log(banana.description()); // banana is yellow

Enter fullscreen mode Exit fullscreen mode

In the example provided above, we observe encapsulation by defining the description method within a class definition.

2nd core fundamental | INHERITANCE

The inheritance skill is for reusing our code with other classes.
In order to show that a class belongs to a superclass, we use the extends keyword.

const Person = class {
   constructor(name, age) {
      this.name = name;
      this.age = age;
   }
}

const Student = class extends Person {

}
const Teacher = class extends Person {

}

const student1 = new Teacher("Jill", 20);
console.log(student1); // output: { name: "Jill', age: 20 }
Enter fullscreen mode Exit fullscreen mode

In these examples, we see how we can extend our superclass Person to Student or Teacher because a teacher or a student is still a person.

By adding the keyword extends, it will take everything that represents a person and append it to the new Student, Teacher, or normal Person.

const Person = class {
   constructor(name, age) {
      this.name = name;
      this.age = age;
   }
}

const Student = class extends Person {

}

const Teacher = class extends Person {

}

const musician = new Person("Bob", 40);
const student1 = new Student("Tim", 10);
const teacher1 = new Teacher("Birusha", 20);

console.log(musician); // output: { name: "Bob", age: 33}
console.log(student1); // output: { name: "Tim", age: 10}
console.log(teacher1); // output: { name: "Birusha", age: 20}
Enter fullscreen mode Exit fullscreen mode

With the power of inheritance, we can add other properties to the class


const Person = class {
   constructor(name, age) {
      this.name = name;
      this.age = age;
   }
}

const Student = class extends Person {
   constructor(name, age, major) {
      this.name = name;
      this.age = age;
      this.major = major;
   }
}

const Teacher = class extends Person {
   constructor(name, age, subject) {
      this.name = name;
      this.age = age;
      this.subject = subject;
   }
}

const musician = new Person("Bob", 40, "CS");
const student1 = new Student("Tim", 10);
const teacher1 = new Teacher("Birusha", 20, "Chemistry");

console.log(musician, student1, teacher1); // error: must call super constructor before using this
Enter fullscreen mode Exit fullscreen mode

The error described above shows that before using properties of the superclass, we must call the superclass constructor.

const Person = class {
   constructor(name, age) {
      this.name = name;
      this.age = age;
   }
}

const Student = class extends Person {
   constructor(name, age, major) {
      super(name, age);
      this.major = major;
   }
}

const Teacher = class extends Person {
   constructor(name, age, subject) {
      super(name, age);
      this.subject = subject;
   }
}


const musician = new Person("Bob", 40);
const student1 = new Student("Tim", 10, "CS");
const teacher1 = new Teacher("Birusha", 20, "Chemistry");

console.log(musician); // output: { name: "Bob", age: 40 }
console.log(student1); // output: { name: "Tim", age: 10, major: "CS" }
console.log(teacher1); // output: { name: "Birusha", age: 20, subject: "Chemisty" }
Enter fullscreen mode Exit fullscreen mode

3rd core fundamental | POLYMORPHISM

In object-oriented programming, polymorphism refers to the ability of objects to take on multiple forms or to be used in various ways. The term "poly" means "many," and "morph" means "form," so polymorphism essentially means "many forms.

Polymorphism is a key concept in object-oriented programming that promotes code reuse, flexibility, and the ability to work with objects in a more generic and abstract manner.

const Fruit = class {
   constructor(name, color) {
      this.name = name;
      this.color = color;
   }

   description() {
      return `${this.name} : ${this.color}`
   }
};

const apple = new Fruit('apple', 'red');
const avocado = new Fruit('avocado', 'green');


console.log(apple.description()); // output: apple : red
console.log(avocado.description()); // output: avocado : green

Enter fullscreen mode Exit fullscreen mode

With these concepts, we have the function "description()" which can display information in several ways depending on the instance created.

4th core fundamental | ABSTRACTION

The last key is abstraction. If we consider that we will need to pay each worker according to their data, we will need to abstract the method of calculating payment. Abstraction allows us to hide what does not matter and show only what is necessary, similar to a remote for a TV. We don't need to know what electronic devices are inside; we just need to click buttons like play.


const Worker = class {
   constructor(name, sup) {
      this.name = name;
      this.sup = sup;
      this.salaryPerHours = 50;
   }

   showSalary () {
      return `${this.name} : $${this.salaryPerHours * this.sup}`;
   }
};


const worker1 = new Worker("Jill", 3);
const worker2 = new Worker("Abel", 10);
const worker3 = new Worker("Jenny", 15);
console.log(worker1.showSalary())
console.log(worker2.showSalary());
console.log(worker3.showSalary());

Enter fullscreen mode Exit fullscreen mode

In this tutorial, we learned about the four core fundamentals of object-oriented programming:

  1. Encapsulation,
  2. Inheritance,
  3. Polymorphism, and
  4. Abstraction.

I hope we will stay in touch for another tutorial. Thank you for giving your time.

Happy Coding... 🚚🚚🚚🚀🚀🚀🚀

Top comments (0)