Object-Oriented Programming (OOP) in JavaScript

Ceren Şolpan Türe
2 min readJan 16, 2021
https://blog.alexdevero.com/fun-object-oriented-javascript/

Object-Oriented Programming (OOP) is the programming model that focuses on objects. Objects are the basic building blocks that we build applications. Which concepts are more preferred? Which ways will we use it? In this article, I will try to explain them.

OOP Concepts in JavaScript

  • Abstraction shows the main features of the object and hides details. It is important because it helps avoid code duplication.
  • Encapsulation aims to hide data and ensure to prevent access from the outside.
  • Inheritance refers to the object to take on the properties and methods of another object.
  • Polymorphism refers to multiple objects use the same functionality and perform a single action in a different way.

How to create ‘class’?

class User {
constructor(name,age) {
this.name = name;
this.age = age;
this.playlist = [];
}
}

The constructor function contains the basic properties of the class. These properties will be unique and defined on each User. In the constructor function, this indicates User and also let to access values.

If we want to define someone as a User, we can create a new User object that specified features.

const ceren = new User('Ceren',29);console.log(ceren.name) // Ceren
console.log(ceren.age) // 29

How to create methods for class?

class User {
constructor(name,age) {
this.name = name;
this.age = age;
this.playlist = [];
}
addPlaylist(song) {
this.playlist.push(song);
}
}

In the example given above, we create addPlaylist method for adding songs to User.playlist. We are adding songs to the playlist with the ‘push’ command. But how do we create the songs that we want to add?

Firstly, we create a new class Song and create a new object/objects.

class Song {
constructor(name) {
this.name = name;
}
}
const lucky = new Song('Lucky');
const downtown = new Song('Downtown');
console.log(lucky.name) // Lucky
console.log(downtown.name) // Downtown

Secondly, we need to add the Song objects that created to the User’s playlist. We make this using the addPlaylist method that created before.

ceren.addPlaylist(lucky);
ceren.addPlaylist(downtown);
console.log(ceren.playlist)

As we can see on the console, songs have been assigned to the user’s playlist.

I tried to explain Object-Oriented Programming in a simple and basic form. If you want to see more details, you can review my codes on my Github profile.

If I have any mistakes, please feedback to me.

Thank You!

You can reach out to me here,

LinkedIn: https://www.linkedin.com/in/cerensolpan/

GitHub: https://github.com/cerensolpan

--

--