Skip to main content

Command Palette

Search for a command to run...

Understanding Object-Oriented Programming in JavaScript

Updated
7 min read

What are we gonna Study?

So, today we are going to study about the most fascinating topic in JavaScript that is, Object-Oriented Programming (OOPS). The topics covered are listed given below:

  • What is Object-Oriented Programming?

  • OOPS Basics (Class, Constructor, Methods)

  • Basics of Encapsulation

I promise that you would absolutely love this blog, you'll understand the basics of OOPS in such a way that you would be able to teach it to anybody else.

Don't worry i would make the complex topics simple. So, sit back relaxed and have a chai ☕


Object-Oriented Programming System (OOPS) in JavaScript

History of OOPS in JavaScript?

First of all JavaScript isn't actually Object-Oriented... Surprised to hear that right?

  • Actually, JavaScript was initially prototype-based programming language.

  • But due to demand and rising popularity of OOPS, they introduced class in their ES6 version.

  • The OOPS in JavaScript are just syntactic sugar.

  • But still, under the hood JavaScript is a Prototype-based programming language.

  • Even if JavaScript became Object-Oriented that would led to a lot of breaking changes.

And this is the reason that if you had ever coded in any other programming language, like Java, Python, C, etc. You would feel that JavaScript is somehow different than those.


What is OOPS?

So, we understood the history, let's understand what actually Object-Oriented Programming truly is?

  • So, OOPS are a programming paradigm (way of writing) where the code structure revolves around Objects not functions or procedures.

  • OOPS makes the code reusable! because you create a blueprint once and next time you just have to type a single line to utilize that whole blueprint. The next section is all about that

  • There are 4 major pillars of OOPS, which are; Encapsulation, Inheritance, Polymorphism, and Abstraction.

We'll discuss the basics of OOPS and Encapsulation.


Class Keyword in JavaScript OOPS

Reality Check:

  • Class is the keyword that separates Object-Oriented language from Prototype-Based language.

  • Although, JavaScript supports class keyword, it's just a syntactic sugar, under the hood it still uses those prototype-based constructor functions.


What is class keyword

Hmm.... we have discussed a lot about history and reality, let's now understand about the actual code :)

  • class keyword is like a blueprint that tells how an object must be created?, which methods should that have?

  • Here is the syntax of class keyword:

// Syntax

class ClassName {...}


// Example

class User {...}
class Animal {...}

Constructor Function in JavaScript

  • Constructor is a function declared inside a class that runs for every object created with that particular class using the keyword new.

  • It is declared using constructor keyword and it can take parameters as well passed at the time of object creation.

  • Let's understand directly with the code.

class Animal {
  constructor(name, species) {
    this.name = name;
    this.species = species;
    console.log(
      `Created an animal named \({this.name} of species \){this.species}`,
    );
  }
}

const dog = new Animal("Buddy", "Dog");
console.log(dog.name) 
console.log(dog.species)

// 1. Created an animal named Buddy of species Dog
// 2. Buddy
// 3. Dog

Let's dry run the code, to understand what is actually happening in this whole code.

  • So, first we are declaring a class Animal and remember it's a blueprint that means it will create new objects.

  • Then, we are declaring a constructor function in that class, which takes 2 things as parameters name, species .

Now, gather all of your focus because you are now at the most important part, if you understand it, then you would understand what OOPS is all about.

  • we are saying this.name = name and this.species = species , here this refers to the current context, and the current context here would be what? Think about it? The curent context her is... the object created using that class.

  • So, basically, here the constructor function will create a key name and another key species and assign that with the value of name and species that it takes as parameter.

  • The creation and assignment process will be executed as soon as an object will be created using that class, reason is simple, because the constructor function runs as soon as an object is created using a class.

Th

e last 3 points are extremely important, i have told them in the simplest language possible.

It's good if you got that, but in case you didn't just read these points one more time and try to visualize that and link that with the code.


Methods in Class

  • Methods are just functions declared inside a class, but unlike constructor function they don't run immediately after the creation of an instance (object created using class).

  • Let's understand the creation of a method and it's use.

// Syntax

class ClassName {
  constructor(params) {...}
  
  methodName(params) {...}
}


// Example

class Animal {
  constructor(name, species) {
    this.name = name;
    this.species = species;
  }

  greet() {
    return `Hello, I am a \({this.species} and my name is \){this.name}.`;
  }
}

const dog = new Animal("Buddy", "Dog");
console.log(dog.greet());

// Output: Hello, I am a Dog and my name is Buddy

See, we don't need the greet to be called immediately right? So, we created a method for it.

  • The greet() is inside the instance that is why it has access to this.name, this.species.

  • It can take parameter as well (if needed).


Encapsulation Basics Along with Hands-on Challenge

  • Encapsulation refers to restricting data access to object.

  • It's like vending machine where the soda or snacks(data) are kept restricted from direct access and buttons (methods) provide you what you want.

  • In today's JavaScript, You can restrict the data just by putting a hash (#) at the beginning.

Let's understand it better by coding a small problem.

// You have to create a class for BankAccount where there is a constructor method that adds the property of owner to the instance, there must be 3 methods: 'deposit', 'withdraw' and 'balance'. Keep the bankBalance restricted.

class BankAccount {
  #balance = 0;

  constructor(owner) {
    this.owner = owner
  }

  deposit(amount) {
    if (amount <= 0) {
      console.log(`Deposit amount must be greater than 0`)
    } else {
      this.#balance += amount
      console.log(`Amount ${amount} is deposited!`)
      console.log(`Balance: ${this.#balance}`);
    }
  }

  withdraw(amount) {
    if (amount <= 0) {
      console.log(`Withdraw amount must be greater than 0`)
    } else if (amount > this.#balance) {
      console.log(`Insufficient balance! Current Balance: ${this.#balance}`);
    } else {
      this.#balance -= amount
      console.log(`Amount ${amount} is withdrawn!`)
      console.log(`Balance: ${this.#balance}`);
    }
  }

  getBalance() {
    console.log(`Balance: ${this.#balance}`);
  }
}

const myAcc = new BankAccount ('Ved');

console.log(myAcc.#balance); // Uncaught SyntaxError: Private field '#balance' must be declared in an enclosing class
myAcc.deposit(1000); // Amount 1000 is deposited! Balance: 1000
myAcc.withdraw(500); // Amount 500 is withdrawn! Balance: 500
myAcc.getBalance(); // Balance: 500
myAcc.withdraw(600); // Insufficient balance! Balance: 500
myAcc.deposit(-200); // Deposit amount must be greater than 0
myAcc.withdraw(-100); // Withdraw amount must be greater than 0
  • Now i waited until now to tell you why it is important to use Encapsulation, because i wanted you to have a code of to understand the why.

  • The reason is pretty simple if we made #balance accessible, anyone can make their balance 1 billion dollars... Will you pay that money? 💀

  • That's the most relatable example of understanding it... Nice job! we have done right? Go through this code and try to code this yourself. That would be a great practice.


Assignments and Wrap Up!

Assignments

  1. Create a class called Student (Use your favorite anime characters as students)

  2. Add properties like name and age

  3. Add a method that prints student details

  4. Create multiple student objects


Wrap Up!

As i promised in the very beginning this blog made your concepts crystal clear, isn't that right?

I hope you loved this one, next up we'll talk about this, bind(), call(), apply() so stay tuned for them i'll drop that one soon!

Update: Hey guys here is the link of the blog we talked about, Read this, call(), bind(), apply(), blog

I'll catch you up in the next blog until then keep coding and enjoy rest of your chai ☕💝

JavaScript: Everything you should know

Part 10 of 26

This is your ultimate guide towards JavaScirpt, this series of articles include - JavaScript Operators: The Basics You Need to Know - Understanding Variables and Data Types in JavaScript - Template Literals in JavaScript - Control Flow in JavaScript: If, Else, and Switch Explained - Array Methods You Must Know - JavaScript Arrays 101 - Function Declaration vs Function Expression: What’s the Difference? - Arrow Functions in JavaScript: A Simpler Way to Write Functions - Understanding Objects in JavaScript - Spread vs Rest Operators in JavaScript - Destructuring in JavaScript - Map and Set in JavaScript - Understanding Object-Oriented Programming in JavaScript - Understanding the this Keyword in JavaScript - The new Keyword in JavaScript - The Magic of this, call(), apply(), and bind() in JavaScript - Array Flatten in JavaScript - String Polyfills and Common Interview Methods in JavaScript - Synchronous vs Asynchronous JavaScript - Callbacks in JavaScript: Why They Exist - JavaScript Promises Explained for Beginners - Promise Methods Explained: CID Analogy - Async/Await in JavaScript: Writing Cleaner Asynchronous Code - Error Handling in JavaScript: Try, Catch, Finally - JavaScript Modules: Import and Export Explained - The Part of Events You Never See The following 26 articles and topics are covered

Up next

The Magic of this, call(), apply(), and bind() in JavaScript

What are we gonna Study? I bet this blog will make your concepts of this, call(), bind(), and apply() crystal clear. Today we'll cover the following topics: What is this keyword? this inside functio

More from this blog

L

Learning Tech

61 posts

A Blog with dozens of articles on different langauges as well as frameworks, This isn't just for you to learn, i crafted it thinking that this could be my future reference as well

It covers Networking, Web Development, Mobile Developement and very soon GenAI too!