-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
JavaScript classes are a modern way to create objects and work with object-oriented programming concepts such as encapsulation, inheritance, and methods. Classes provide a clean and structured approach to defining blueprints for objects, making your code more organized, readable, and maintainable. They are a syntactical improvement over constructor functions, offering a more intuitive way to create and manage objects.
In this tutorial, you will learn about JavaScript classes, how to define and use them, practical examples, common mistakes, best practices, and real-world applications.
Classes are important in JavaScript because they allow you to:
Create multiple objects with similar structures and behaviors
Encapsulate data and methods within a single, reusable blueprint
Implement object-oriented programming principles efficiently
Make code more organized and maintainable
Enable inheritance to extend functionality from other classes
Without classes, developers would need to rely on constructor functions and prototypes, which can become cumbersome and harder to manage in complex applications.
A class in JavaScript is defined using the class keyword, followed by the class name and a body enclosed in curly braces. By convention, class names start with a capital letter.
class Student {
constructor(name, age, course) {
this.name = name;
this.age = age;
this.course = course;
}
greet() {
console.log("Hello, my name is " + this.name);
}
}
Here, constructor is a special method used to initialize new objects. The greet method is a class method that can be called on any instance of the class.
Once a class is defined, you can create new objects using the new keyword:
const student1 = new Student("Aarushi", 20, "JavaScript");
const student2 = new Student("Priya", 22, "React");
console.log(student1.name); // Aarushi
student2.greet(); // Hello, my name is Priya
Each object created from the class has its own set of properties, while methods defined in the class are shared across instances.
Class methods are functions defined inside the class that can interact with instance properties using this. They allow encapsulated behavior within the class.
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
celebrateBirthday() {
this.age += 1;
console.log(this.name + " is now " + this.age + " years old");
}
}
const student = new Student("Saanvi", 21);
student.celebrateBirthday(); // Saanvi is now 22 years old
Methods help keep related behavior and data together, making the class a self-contained unit.
JavaScript classes also support getters and setters, which provide controlled access to object properties.
class Student {
constructor(name, age) {
this._name = name;
this._age = age;
}
get name() {
return this._name;
}
set age(value) {
if (value > 0) {
this._age = value;
} else {
console.log("Invalid age");
}
}
}
const student = new Student("Isha", 22);
console.log(student.name); // Isha
student.age = 23;
console.log(student._age); // 23
Getters and setters provide a layer of validation and encapsulation for properties.
Static methods are functions defined on the class itself rather than on instances. They are useful for utility functions related to the class but not specific to an object.
class Student {
static schoolInfo() {
console.log("All students belong to XYZ School");
}
}
Student.schoolInfo(); // All students belong to XYZ School
Static methods cannot be called on individual objects; they are only accessible via the class.
Classes in JavaScript support inheritance using the extends keyword. This allows one class to inherit properties and methods from another class.
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log("Hello, my name is " + this.name);
}
}
class Teacher extends Person {
constructor(name, subject) {
super(name);
this.subject = subject;
}
teach() {
console.log(this.name + " is teaching " + this.subject);
}
}
const teacher = new Teacher("Saanvi", "Math");
teacher.greet(); // Hello, my name is Saanvi
teacher.teach(); // Saanvi is teaching Math
The super keyword calls the constructor of the parent class, enabling inheritance of properties and methods.
Forgetting to use new when creating an instance, which causes errors
Misusing this inside class methods, especially in callbacks
Overwriting methods or properties accidentally
Confusing static methods with instance methods
Forgetting to call super() in subclasses
Use descriptive class names with capitalization
Keep classes focused on a single responsibility
Use getters and setters for controlled property access
Use inheritance only when logically necessary
Encapsulate methods that operate on instance data within the class
Creating models for users, students, products, or courses
Organizing code in object-oriented applications
Encapsulating state and behavior in frontend frameworks like React or Angular
Building reusable components and libraries
Implementing inheritance for extending functionalities
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log("Hello, my name is " + this.name);
}
}
const student = new Student("Aarushi", 20);
student.greet();
class Student {
constructor(name, age) {
this._name = name;
this._age = age;
}
get name() {
return this._name;
}
set age(value) {
if (value > 0) {
this._age = value;
}
}
}
const student = new Student("Priya", 22);
student.age = 23;
console.log(student._age);
class Person {
constructor(name) {
this.name = name;
}
}
class Teacher extends Person {
constructor(name, subject) {
super(name);
this.subject = subject;
}
teach() {
console.log(this.name + " teaches " + this.subject);
}
}
const teacher = new Teacher("Saanvi", "Math");
teacher.teach();
teacher.greet = function() { console.log("Hello from teacher"); };
teacher.greet();
JavaScript classes provide a structured way to define objects, encapsulate data, and implement object-oriented programming concepts. They allow the creation of multiple objects with shared properties and methods, support inheritance, and offer features like getters, setters, and static methods. Proper use of classes improves code readability, maintainability, and scalability, making them essential for modern JavaScript development.
Basic Class Creation
Create a class Person with properties firstName and lastName. Add a method fullName() to return the full name. Instantiate an object and log the full name.
Constructor with Multiple Properties
Create a class Student with firstName, lastName, and grade. Create two instances and log their properties.
Getters and Setters
Add a getter and setter for grade in the Student class to validate the grade is between 0 and 100. Test with valid and invalid values.
Static Method
Create a class Calculator with a static method multiply(a, b). Call it directly from the class and verify it cannot be called on an instance.
Instance Method vs Static Method
Create a class Car with an instance method info() and a static method compare(). Instantiate objects and test both methods.
Inheritance
Create a class Animal with a method speak(). Extend it with a class Cat that overrides speak() to print a custom message.
Using super()
In a child class, call the parent constructor using super() and verify that inherited properties are correctly initialized.
Private Fields
Create a class BankAccount with a private field #balance. Add methods to deposit money and check balance. Attempt to access #balance directly.
Multiple Instances Sharing Methods
Show that two instances of a class share the same method reference by comparing the function references.
Computed Method Names
Define a method in a class using a computed property name (e.g., [methodName]()) and call it on an instance to demonstrate dynamic method definition.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
