In web development, it is important for you to learn how to work with objects and classes. If you want to organize your JavaScript code in a clean and efficient way, then you have to have a good understanding of JavaScript OOP. Object-oriented programming is a way of writing code where related data and actions are grouped into objects. This makes your code easier to reuse, manage, and understand.
In this blog, we will talk about OOP and its various concepts in JavaScript. We will also talk about their implementation and their applications. So let’s get started!
Table of Contents:
What is OOP (Object Oriented Programming)?
Object Oriented Programming (OOP) is a way of writing code where you can keep the related information (like data) and actions (like functions) together in one place. This is the same as how objects in the real world work.
Note: JavaScript is not a totally object-oriented programming language or a completely functional language. It is a flexible language that follows a prototype-based style and allows you to write your code in both object-oriented and functional programming methods.
There are two types of OOP languages:
1. Class-Based Languages: Java, C++
2. Prototype-Based Languages: JavaScript.
Is JavaScript Object Oriented?
To understand whether JavaScript is object-oriented or not, you need to understand the difference between OOP and Prototype-based programming.
Object Oriented Programming (OOP): In object-oriented programming, all the related data and actions are grouped together inside a class. Then you use that class to create real examples of it, which are known as objects.
Prototype-based programming: In Prototype-based programming, you have to create new objects by copying or reusing the features from other existing objects.
JavaScript is basically a Prototype-based programming paradigm. However, it still supports the OOP features. The class keyword in JavaScript is just a simple way to work with prototypes. It makes your code look Object-Oriented, but behind the scenes, JavaScript uses prototypes and not real classes.
Everything in JavaScript is an object. When you create an array and print it in the console, you will notice some extra properties like length, even though you didn’t add them. These properties come from the built-in features of JavaScript that are added automatically to your array. We have added a sample code below for your understanding:
Code:
Output:
Explanation:
In this code, you create an array called shoppingList with a few items. When you print the array, you also check its length property, which shows how many items it has. Even though you didn’t manually add the length property, JavaScript automatically includes it. Then, using a for…in loop, you list all the keys in the array, including the ones that are inherited from its prototype. Finally, you check if length exists in the array and whether it’s directly part of the array or inherited. This shows how JavaScript adds built-in features to objects like arrays automatically.
Hence, we can conclude that an array is also an object in JavaScript. In the same way, everything in JavaScript is an object. No matter what you create, like an array or a function, they always get extra features from something called a prototype. This is how JavaScript provides your code with the built-in properties, and you don’t have to write them yourself.
Master Web Development
Learn to Build Stunning Websites and Apps from Scratch
Key OOPS Concepts in JavaScript
JavaScript allows you to use it by providing you with features that help you to work with objects, classes, and object-oriented concepts. The key aspects of Object Oriented Programming in JavaScript are given below:
1. Objects
In JavaScript, an object is a special type of data that allows you to store collections of key-value pairs. Each key in JavaScript is called a property, and each property has its own value. Objects help you to group the related data and functions together in one place. This helps to make your code more organized and easier to manage.
An example of Objects in JavaScript is given below for your reference:
Code:
Output:
Explanation:
In the above example, the object named person consists of properties like name and age, and a method called greet. This method prints a message using the data of the object named person.
2. Classes
Classes in JavaScript provide you with a simple way to create objects. They help you to group the related data (properties) and actions(methods) together in one place. To create a class, you can use the class keyword, and then you can make real objects from it by using the new keyword.
An example of Classes in JavaScript is given below for your reference:
Code:
Output:
Explanation:
The above code is used to define a class named Rectangle. Inside the class, there is a constructor that takes the width and height as inputs and stores everything in the object. It also consists of a method called getArea() that is responsible for calculating the area by multiplying the width and height. After that, an object named rect is created from the Rectangle class with the help of the new keyword. At last, the getArea() method is called to print the area.
3. Encapsulation
In JavaScript, Encapsulation means storing the related data and methods together into a single unit, inside a class or object. This helps in securing the valuable information so that it is not directly changed and makes your code cleaner and easier to maintain. This can be done by using private fields and by adding a “_” before the name of the property.
An example of Encapsulation in JavaScript is given below for your reference:
Code:
Output:
Explanation:
The above JavaScript code is used to define a class named BankAccount. Here you can set the initial balance and add money with deposit(). You can also check your balance using getBalance(). The _balance property is kept private, even though it can be accessed directly.
4. Inheritance
Inheritance in JavaScript helps one class to take features from another class, so that you don’t have to repeat the code. The new class (child) gets all the properties and methods from the parent class and can also have its own properties.
An example of Inheritance in JavaScript is given below for your reference:
Code:
Output:
Explanation:
The above describes how the class named Dog inherits the speak() method from its parent class Animal and then adds it to its own method bark().
5. Polymorphism
In JavaScript, Polymorphism means that different classes can have methods that have the same name, but each class can define it in its own way of how that particular method works. Polymorphism allows you to use the same method in different ways.
An example of Polymorphism in JavaScript is given below for your reference:
Code:
Output:
Explanation:
The above shows how both Cat and Dog use the same name, makeSound(), but they both give different results. This is how Polymorphism works.
6. Abstraction
In JavaScript, Abstraction means hiding all the complex details of the code and showing only the necessary items. It helps you to work with simpler interfaces while keeping the logic hidden inside a class or a function.
An example of Abstraction in JavaScript is given below for your reference:
Code:
Output:
Explanation:
The above JavaScript code shows abstraction. It uses startCar() as the main method, while hiding the logic of the engine _startEngine(). You can use one method and avoid the internal details.
What is Prototypal Inheritance in JavaScript?
The Prototypal Inheritance is a mechanism in JavaScript in which one object inherits methods or properties from another object. Instead of copying the code, JavaScript links objects together. When you try to access a property on an object and you find out that it does not exist, JavaScript uses the prototype chain to find it. This enhances memory as well as the flexibility of your code since the methods can be shared by multiple objects without replicating them.
An example code is given below for your reference:
Code:
Output:
Explanation:
In the above example, the object dog does not have its own speak() method. It inherits the method from the animal class through the prototype chain.
Get 100% Hike!
Master Most in Demand Skills Now!
How to Implement Prototypal Inheritance in JavaScript
There are three main ways to implement prototypal inheritance in JavaScript. They are explained below:
1. Using Constructor Functions
In JavaScript, you can make objects with the help of a function called a constructor. Built-in objects like arrays and sets are also made in the same way. By using the new keyword, the constructor function runs and creates a new object. It then sets the starting values for the properties of that object.
Code:
Output:
Explanation:
The above JavaScript code creates an object Dog that inherits from the Animal class using constructor functions. It uses the speak() method from the Animal class with the help of the prototype chain.
2. Using ES6 Classes
In JavaScript, ES6 introduced two keywords: class and extends to make inheritance easier to use and understand. You can create a base class with common properties and methods, and then use the extends keyword to create a new class on top of it. This helps to write cleaner and efficient code.
Code:
Output:
Explanation:
The above code uses ES6 classes for inheritance. The Dog class uses extends to inherit properties from the Animal class, so that it gets the name and speak() method automatically. It then adds its own method bark(). When you create a Dog object like a pet, it can use both the methods, speak() and bark().
3. Using Object.create()
This is the third and simplest way to use prototypal inheritance in JavaScript. You can make a new object that connects directly to another object, so that it can use the properties and methods of that object.
Code:
Output:
Explanation:
The above JavaScript code shows prototypal inheritance. The car object is created from the vehicle class; hence, it inherits the start() method. The car object also has its own drive() method.
Applications of JavaScript OOP
Some applications of JavaScript OOP are given below:
1. Building Reusable UI Components: You can create buttons, sliders, or forms as objects and reuse them in your web application.
2. Organize code in Large Projects: OOP helps you to keep your code neat when you are working on large applications.
3. Working with Frontend Frameworks: Frontend frameworks like React and Angular use the concepts of OOP to build apps in a more effective way.
4. Managing App Data and Behavior: You can also store and update data with the help of objects, which helps to make your app smart.
Conclusion
JavaScript Object-Oriented programming (OOP) simplifies how you organize, reuse, and understand your code. Regardless of whether you are creating a user interface, a game, or a full web app, OOP helps you to organize your work in a clean and logical manner. Through simple means such as constructor functions, classes, and prototypal inheritance, you can develop powerful features without any kind of duplication. After you learn how to use it, JavaScript OOP is a very useful technique in the life of any developer. If you are an aspiring Web Developer, then explore our blog and enroll in our Web Development Course.
Object Oriented Programming in JavaScript – FAQs
Q1. Is JavaScript a purely object-oriented language?
No, JavaScript is a multi-paradigm language that supports object-oriented as well as functional styles.
Q2. Do I need classes to use OOP in JavaScript?
No, it is not necessary. You can also use constructor functions and prototypes.
Q3. Can I create private properties in JavaScript objects?
Yes, in order to create private properties in JavaScript objects, you can use the “#” symbol.
Q4. Is OOP in JavaScript good for small projects?
Indeed, even small projects can take advantage of the better code structure and reuse with the help of OOP.
Q5. What is the main benefit of using OOP in JavaScript?
It helps you to organize your code in a better way, especially as your application is growing.