JavaScript classes were introduced in ES6 (ECMAScript 2015) to provide a clearer and more structured way to create objects and implement object-oriented programming.
A class acts as a blueprint for creating objects. It defines the properties and methods that objects created from that class can have.
Before ES6, developers commonly used constructor functions and prototypes to create objects with shared behavior. The class syntax provides a more familiar and organized way to write this code.
In this tutorial, you will learn how to create classes, use constructors, define methods, create objects with the new keyword, and understand how JavaScript classes work.
What Is a Class in JavaScript?
A class is a template for creating objects with shared properties and methods.
For example, if you are developing a student management application, you might need multiple student objects. Each student may have a name, age, and method for displaying their details.
Instead of creating every object separately, you can define a Student class and use it to create multiple student objects.
JavaScript Class Syntax
The basic syntax of a JavaScript class is:
class ClassName {
constructor() {
// Initialize object properties
}
methodName() {
// Define a method
}
}
The class keyword declares a class. The constructor() method initializes an object when it is created, and other methods define the behavior of its instances.
Example of a JavaScript Class
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
displayDetails() {
console.log(`Name: ${this.name}`);
console.log(`Age: ${this.age}`);
}
}
const student1 = new Student("Rahul", 20);
student1.displayDetails();
Output:
Name: Rahul
Age: 20
In this example:
class Studentdefines a class namedStudent.constructor(name, age)receives values when an object is created.this.nameandthis.agestore values on the new object.displayDetails()defines a method that displays the student’s information.new Student("Rahul", 20)creates a new student object.
To understand how the resulting objects store their data, you can also learn about JavaScript Objects.
Creating Objects from a Class
An object created from a class is called an instance of that class.
You create an instance by using the new keyword followed by the class name and any required arguments.
Example
class Car {
constructor(brand, color) {
this.brand = brand;
this.color = color;
}
}
const car1 = new Car("Toyota", "White");
const car2 = new Car("Honda", "Black");
console.log(car1.brand);
console.log(car1.color);
console.log(car2.brand);
console.log(car2.color);
Output:
Toyota
White
Honda
Black
Both objects are created from the same Car class, but each instance has its own property values.
The car1 object stores "Toyota" and "White", while car2 stores "Honda" and "Black".
This makes classes useful when an application needs to create many objects with the same structure.
The Constructor Method
The constructor() method is a special method used to initialize a class instance.
JavaScript automatically calls the constructor when you create an object using new.
Example of a Constructor
class Employee {
constructor(name, role, salary) {
this.name = name;
this.role = role;
this.salary = salary;
}
}
const employee1 = new Employee("Priya", "Developer", 35000);
console.log(employee1.name);
console.log(employee1.role);
console.log(employee1.salary);
Output:
Priya
Developer
35000
When new Employee() runs, JavaScript creates a new object and calls the constructor with the supplied arguments.
The this keyword refers to the newly created instance while the constructor executes.
A Class Without an Explicit Constructor
You do not always need to write a constructor. If a class does not define one, JavaScript provides a default constructor.
class Message {
show() {
console.log("Welcome to JavaScript!");
}
}
const message = new Message();
message.show();
Output:
Welcome to JavaScript!
Because the class does not require any initial values, an explicit constructor is unnecessary.
Defining Methods in a Class
Methods are functions defined inside a class that describe what its instances can do.
You write class methods using the method name followed by parentheses and a block of code. You do not need to use the function keyword.
Example of Class Methods
class Calculator {
add(a, b) {
return a + b;
}
subtract(a, b) {
return a - b;
}
multiply(a, b) {
return a * b;
}
}
const calculator = new Calculator();
console.log(calculator.add(10, 5));
console.log(calculator.subtract(10, 5));
console.log(calculator.multiply(10, 5));
Output:
15
5
50
The Calculator class defines three methods. The calculator instance can call each method using dot notation.
Class methods are generally shared through the class prototype rather than being recreated as separate own properties on every instance.
Using this Inside a Class
The this keyword allows you to access properties and methods associated with the current object.
When you call an instance method through an object, this normally refers to that object.
Example
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}!`;
}
}
const person1 = new Person("Ayesha");
const person2 = new Person("Arun");
console.log(person1.greet());
console.log(person2.greet());
Output:
Hello, Ayesha!
Hello, Arun!
The same greet() method produces different results because each object has a different name property.
In a class method, this depends on how the method is called. If you extract a method and call it as a standalone function, its this value is not automatically bound to the original instance.
Class Expressions in JavaScript
You can define a class using a class expression and assign it to a variable. A class expression can be named or anonymous.
Example of an Anonymous Class Expression
const Animal = class {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
};
const animal = new Animal("Dog");
console.log(animal.speak());
Output:
Dog makes a sound.
Here, the class expression is assigned to the Animal variable. You can use that variable to create instances.
Example of a Named Class Expression
const Vehicle = class VehicleType {
showType() {
return "This is a vehicle.";
}
};
const vehicle = new Vehicle();
console.log(vehicle.showType());
Output:
This is a vehicle.
A named class expression can refer to its internal class name from within the class body. Outside the expression, you generally use the variable to access the class.
Important Rules of JavaScript Classes
JavaScript classes have several important characteristics:
- Class declarations are not available before their declaration is evaluated. Although classes have a temporal dead zone like
letandconst, they cannot be used before their declaration is initialized. - Classes must be called with
new. Calling a class like a regular function causes aTypeError. - Class methods are not enumerable properties of the prototype.
- Class methods execute in strict mode.
- A class can contain one constructor method for initializing instances.
- Class declarations cannot be redeclared in the same scope.
For example, this code causes an error:
class User {
constructor(name) {
this.name = name;
}
}
// TypeError: Class constructor User cannot be invoked without 'new'
// User("Rahul");
The correct way to create an instance is:
const user = new User("Rahul");
console.log(user.name);
Output:
Rahul
JavaScript Classes vs Constructor Functions
Before ES6, constructor functions were commonly used to create objects with shared behavior.
Using a Constructor Function
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return `Hello, ${this.name}!`;
};
const person = new Person("Rahul");
console.log(person.greet());
Output:
Hello, Rahul!
Using a Class
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hello, ${this.name}!`;
}
}
const person = new Person("Rahul");
console.log(person.greet());
Output:
Hello, Rahul!
Both approaches can create objects with similar behavior. JavaScript classes provide a more convenient syntax for working with constructors, methods, inheritance, and related object-oriented programming features.
Classes are not a completely separate object system. JavaScript classes use prototypes behind the scenes.
Frequently Asked Questions
What is a class in JavaScript?
A class is a template for creating objects with shared properties and methods. You can use it to create multiple instances with different data.
Why are classes used in JavaScript?
Classes help organize code when working with objects that share common properties and behavior. They are especially useful for larger applications and object-oriented programming.
What is the purpose of the constructor in a JavaScript class?
The constructor initializes a new instance. It commonly assigns initial values to properties using arguments passed when the object is created.
Can a JavaScript class have multiple constructors?
No. A class can define only one constructor() method. If you need different initialization behavior, you can use optional parameters, default parameters, or conditional logic inside the constructor.
Can I create an object without using a class?
Yes. JavaScript supports object literals, factory functions, and constructor functions. Classes are one of several ways to create and organize objects.
Are JavaScript classes based on prototypes?
Yes. JavaScript classes use the prototype-based inheritance system. Instance methods are generally stored on the class prototype and shared by instances.
Conclusion
JavaScript classes provide a structured way to create objects and define their properties and methods. The class keyword declares the class, the constructor() method initializes new instances, and methods define the behavior shared by those instances.
Understanding classes is an important step toward learning object-oriented JavaScript. Once you are comfortable with creating classes and instances, you can move on to inheritance, static methods, and other advanced ES6 features.
6 thoughts on “JavaScript Classes”
Comments are closed.