What are Classes and How to Use Them in JavaScript ? 🤔🤔

sandeepnautiyal

Sandeep Nautiyal

Posted on April 24, 2024

What are Classes and How to Use Them in JavaScript ? 🤔🤔

JavaScript, prior to ES6 (ECMAScript 2015), relied on constructor functions to mimic object-oriented concepts. These functions act as blueprints for creating objects, but lack some of the features and structure offered by modern classes.
Let's see a basic implementation of a constructor function for reference...

function Person(name) {
  this.name = name;
  this.greet = function() {
    console.log("Hello, my name is " + this.name);
  };
}
const person1 = new Person("Sandeep");

person1.greet(); // Output: "Hello, my name is Sandeep"
Enter fullscreen mode Exit fullscreen mode

Now the question is if we already have something like this why to introduce something new, why to introduce classes, well thing is these functions have some limitations for example:-

No Inheritance: While you can mimic inheritance patterns using prototypes, it's less straightforward compared to classes.
Verbosity: Defining methods within the constructor function can lead to repetitive code, especially for complex objects.

that is why Classes were introduced in ES6 to addressed these shortcomings by providing a more structured and concise way to define objects and their behaviour.

Well Now enough with why they were introduced and let's jump into how to use them properly.

To create a class all you have to do is use a keyword to define it which is called (wait for it, wait for it, drum roll please 🥁 🥁) "class" lol 🤣🤣. Here is a code snippet of a class in action.

class Person{
    constructor(name){
        this.name=name;
    }
    greet(){
        return `Hello, my name is ${this.name}`
    }
}

const sandeep = new Person("sandeep");

console.log(sandeep.greet()); 
//Output:'Hello, my name is sandeep'
Enter fullscreen mode Exit fullscreen mode

Here are some key benefits of using classes in JavaScript:

  • Reusability: Classes allow you to create multiple objects with the same structure and functionality, reducing code duplication.

  • Maintainability: Code is easier to understand and modify when it's organised into classes. Each class encapsulates its own data and logic, making it more self-contained.

  • Object-Oriented Patterns: Classes facilitate the use of common object-oriented design patterns like inheritance and polymorphism ✨

Now your next question will be "Sandeep, we got it, why classes were introduced and how to implement them, but where to implement them? Well, that's something we will discuss in the next article. Until then, happy coding!"

I hope this helps! 😁😁

💖 💪 🙅 🚩
sandeepnautiyal
Sandeep Nautiyal

Posted on April 24, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related