JavaScript classes are blueprints for creating objects with shared properties and methods. Instead of rewriting the same code repeatedly, classes let you define a structure once and reuse it efficiently. Introduced in ES6, they simplify object-oriented programming, making your code cleaner and more organized. In this article, you will learn how to create classes, use constructors, define methods, and apply inheritance, along with key features. Whether you are building games, apps, or scripts, mastering classes will help you write more reusable and maintainable code.
Table of Contents:
What are Classes in JavaScript?
A JavaScript class is a blueprint that describes how a particular object that belongs to that class should behave. It describes all of its properties and methods that you can use with the objects inside that class. When you create a class object in JavaScript, you are ultimately creating a reusable pattern that can generate multiple objects with the same characteristics. To take a very common example, if you want to create multiple car objects, you can define a Car class once and then create as many car objects as needed from that single template.
Why ES6 Introduced Classes in JavaScript
Before ES6 (ECMAScript 2015), JavaScript used simple constructor functions to create objects. This was specific to the JavaScript programming language and was not commonly used in other programming languages. While the constructor method is functional, this approach was often confusing for developers coming from other programming languages. Therefore, to make programming languages more accessible and easy to understand for all, ES6 introduced the JavaScript class syntax. It was done to make object-oriented programming more intuitive and readable.
The introduction of class syntax allowed developers to define object blueprints, implement inheritance, organize related methods and properties, and write more maintainable code. Let us now understand the syntax of JavaScript Classes in detail.
Syntax of JavaScript Classes
Let us first look at how you declare a class in JavaScript, which you do using the class keyword.
Declaring a Class Using the Class Keyword
class ClassName {
// class body
}
Let us declare a Person class in JavaScript using the class keyword. Even though there is no method defined inside the class yet, the code will compile successfully:
Code:
Output:
Explanation: This example shows how, without even declaring any methods inside the class, we were successfully able to create an object and call it without any errors.
Constructor Method
The constructor method is an important method that always runs when you create a new object from the class. The constructor method is used to initialize properties of a Java object:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
Master Web Development
Learn to Build Stunning Websites and Apps from Scratch
A few things you need to keep in mind when you are defining a construction method are:
- The constructor method will always have the name “constructor”.
- It will automatically be called when creating new objects.
- It will set initial values of the properties for that instance of the object.
- It can accept parameters to customize each object according to the requirements in that situation.
Class Methods
The class methods are functions that are defined inside the class that all objects created from the class can use:
Code:
Output:
Explanation: In this code example, the constructor assigns the name and age property variables of the object when the Person object is created, once for Garima and then for Pooja. Then, another introduce() and haveBirthday() methods were defined, which are class methods.
Public Class Fields
Apart from initializing properties inside the constructor, JavaScript also supports public class fields, a simpler way to declare and initialize properties directly within the class body.
const Person = class {
constructor(name) {
this.name = name;
}
};
Creating Objects from a Class
After creating the blueprint of the class, let us understand how to use that class and make an instance of it to use as an object. Each object created in this way, JavaScript has its own set of properties, but they all share the same methods.
Using New Keyword
We create objects using a JavaScript class with the help of the new keyword followed by the class name.
Code:
Output:
Explanation: This example demonstrated how to create an object of the Person class in JavaScript using the new keyword.
Important Features of JavaScript Classes
There are several features that enhance how you organize and manage your code for JavaScript classes. In this section, we will look at such features that will help you write more efficient and readable code for classes in JavaScript.
1. Static Methods
Static methods are functions that belong to the class itself and not to the individual objects you create from it. You call them directly on the class’s name (like MathHelper.add()) without having to create an object first. They are useful for general helper tasks that do not specifically depend on any object data.
Code:
Output:
Explanation: In this code, we simply use the add and multiply methods, like MathHelper.add() or MathHelper.multiply(). We do not first create an object like const calculator = new MathHelper(). This clearly shows that these methods are tied directly to the MathHelper class itself, ready to be used right away.
2. Getters and Setters
Getters and Setters are special methods (functions) inside a class that allow you to control how its properties are read or written. Even though they are functions, you use them as if they were regular properties, that is, without the parentheses.
- A Getter is defined to get a property’s value. When you read the property (meaning when you try to get their value), a hidden function automatically runs behind the scenes to prepare that value for you.
- A Setter is a way to set the value of any of the properties of the object. When you assign a new value to a property, a hidden function automatically runs. This function can also check if the value is valid before saving it.
Code:
Output:
Explanation: In this example of a Rectangle class, area is a getter: when you access rect.area, a hidden method calculates the area. For width, accessing rect.width runs a getter to return its value, while rect.width = 8 activates a setter method to check if the value is valid before updating it. This shows how getters and setters provide controlled access to properties.
Note: The underscore(_) used before width and height here is a convention common amongst JavaScript developers that means that these properties are intended to be used only internally within the class.
Get 100% Hike!
Master Most in Demand Skills Now!
3. Private Elements (#)
Sometimes, there are properties or methods within a class that are only meant to be used as an internal part of that class. You do not want these properties to be able to be changed or accessed from outside the class, and this is where Private Elements take importance.
In JavaScript classes, you can define a property or a method to be a private element by prefixing the property name or method name with a # (hash symbol).
The main rule of private elements is fairly simple:
- A private element can only be accessed from within the class where they are defined.
- You cannot access a private element from an object that was made from that class. If you did, it would throw an error.
This is also a way of creating classes that is clean and segregated, because it is clear what is for internal purposes and what properties can be used for something outside the class.
Code:
Let’s use a simple Person class with a private property for their secret ID.
Output:
Explanation: In this Person class, #secretId is a private property of the class, and #generateInternalCode is a private method. Here, you can access #secretId and call #generateInternalCode() from methods inside the Person class (like showSecretId() or getInternalCode()). However, if you try to directly access ayaan.#secretId from outside the class (the commented-out line), JavaScript will give you an error. This clearly shows how private elements keep certain details hidden and protected within the class.
4. Hoisting Behavior
Hoisting means that JavaScript sometimes moves certain things, like simple functions, to the top of their section of code before it even starts running. But JavaScript classes are different; they are not hoisted.
This means you must write your class definition before you try to use it. If you try to use a class before it has been fully defined in your code, JavaScript will not know what that class is, and you will get an error.
Code:
Output:
Explanation: In the example above, JavaScript tries to create obj from MyClass first. But the MyClass definition comes later. Because classes are not “moved to the top,” JavaScript sees MyClass before it knows what it is. This causes an error, as the class is not yet defined when it’s first used.
JavaScript Inheritance
Class inheritance is another property of classes that allows you to create new classes based on existing ones. The child class inherits the methods and behaviors of the parent class. This saves the time and effort of a developer from writing the same code logic again and again. Let’s understand how to achieve inheritance with JavaScript classes.
Using Extends and Super()
As we discussed above, Inheritance allows you to create a new class based on an existing class. The new class inherits all properties and methods from the parent class. In JavaScript, you can achieve inheritance using the Extend keyword and the super method.
- extends keyword: This keyword is used right after your new class’s name (the child class) to tell JavaScript that it will inherit from another existing class (the parent class). It’s how you set up the connection, allowing the child class to automatically get all the methods and properties from the parent.
class ChildClass extends ParentClass {
// class body
}
- super() method: When you define a constructor in your child class, you must call super() inside it. The super() method calls the constructor of the parent class. It makes sure that all the behaviours and properties that the child is going to inherit are set up correctly before the child class adds their own specific details.
constructor(childArgs) {
super(parentArgs);
// child class initialization
}
Code:
Output:
Explanation: In this example, the Dog class extends Animal and inherits properties like name and species. Here, the Dog class also overrides the makeSound() method. Therefore, when myDog.makeSound() is called, it uses the overridden method in Dog, printing “Buddy barks!”.
Common Mistakes to Avoid When Using JavaScript Classes
As a beginner, you are bound to make mistakes when creating JavaScript Classes because of the lack of practice and familiarity with object-oriented concepts and specific class behaviors of JavaScript. In this section, we will discuss all such beginner mistakes to save you a lot of time and frustration, and help you write cleaner and error-free code from the start.
1. Forgetting New
A very common mistake that beginners tend to make is forgetting the new keyword when creating an object from a JavaScript class. If you call a class like a regular function, something like Person(), you will not properly create an object or set up its properties. Therefore, always use new, like new Person(), to correctly build a new instance of your class.
Mistake:
class Person {
constructor(name) {
this.name = name;
}
}
const user = Person("Akshat"); (new is not used)
Right Syntax:
class Person {
constructor(name) {
this.name = name;
}
}
const user = new Person("Akshat"); (new is used)
2. Misusing ‘this’ Keyword
The this keyword in JavaScript is a bit confusing because it doesn’t always mean the same thing. Its value depends on how the function is called and not just where it was defined. When you use a method from a class (like object.method()), this usually refers to the object itself. But if you call that method separately, or pass it to something like an event listener or callback, it can lose its connection to the original object. You should use arrow functions or bind() to keep the right value of this.
3. Overriding the Constructor Incorrectly
When you create a child class that includes its own constructor function, you must always call super() first inside that constructor. Calling super() ensures the parent class properly sets up its part of the new object before your child class adds its specific details. If you add child class-specific behaviours before calling super(), JavaScript will cause an error.
Limitations of JavaScript Classes Compared to Classical OOP
While JavaScript classes offer a convenient syntax for object-oriented programming, there are some limitations compared to classical OOP languages like Java or C++:
- JavaScript classes are primarily syntactic sugar over prototypes and don’t have true class-based inheritance under the hood.
- There is no support for interfaces or strict access modifiers (public, protected, private) beyond the private fields syntax (#).
- Multiple inheritance is not supported, which can limit some advanced OOP patterns.
- The dynamic nature of JavaScript means type safety and compile-time checks are less strict.
Understanding these limitations helps you write more effective JavaScript code and avoid common pitfalls.
Conclusion
JavaScript classes provide an elegant way to create objects with cleaner syntax for object-oriented programming. Using the class keyword, you can define object templates and use constructor methods within them to initialize properties. Inheritance using the extends and super() syntax allows for reusing code efficiently. JavaScript classes help improve your development in terms of organizing and maintaining your code and improving readability. Classes are an important concept that you need to master to improve the quality of the projects you develop. Overall, practice with this fundamental concept as needed.
JavaScript Classes – FAQs
Q1. What are classes in JavaScript?
You can think of classes as blueprints for creating objects in JavaScript, introduced in ES6 to simplify object-oriented programming.
Q2. Can you learn JavaScript classes in 30 days?
You can learn the basics of JavaScript classes in 30 days with focused practice on syntax, constructors, methods, and inheritance.
Q3. Is mastering JavaScript classes enough to get a job?
You can’t rely only on classes; employers expect you to know JavaScript fundamentals, DOM manipulation, async programming, and popular frameworks too.
Q4. What is the best way to learn JavaScript classes?
You can learn best through hands-on projects and tutorials that cover ES6 classes, inheritance, prototypes, and how classes improve code organisation.
Q5. How do JavaScript classes differ from functions?
You can use classes as syntactic sugar over constructor functions; they offer a cleaner, more intuitive syntax for creating objects and inheritance.