JavaScript Classes Explained with Practical
Examples
Created by Dinisha S
1. Introduction
A class in JavaScript is a blueprint used to create objects. It helps organize code in a clean and
reusable way. Classes allow us to group data (properties) and functions (methods) together.
2. Basic Syntax Example
class Student {
constructor(name, age) {
[Link] = name;
[Link] = age;
}
greet() {
[Link]("Hello, my name is " + [Link]);
}
}
const s1 = new Student("Dinisha", 20);
[Link]();
Explanation: constructor is a special method used to initialize objects. 'this' refers to the current
object created from the class.
3. Real-Life Example
class Laptop {
constructor(brand, ram) {
[Link] = brand;
[Link] = ram;
}
details() {
return `Laptop brand is ${[Link]} with ${[Link]}GB RAM`;
}
}
const myLaptop = new Laptop("Lenovo", 12);
[Link]([Link]());
4. Inheritance Example
class Person {
constructor(name) {
[Link] = name;
}
}
class Teacher extends Person {
subject() {
return [Link] + " teaches JavaScript";
}
}
const t1 = new Teacher("Ms. Anu");
[Link]([Link]());
5. Practice Questions
• 1. Create a class called Employee with name and salary.
• 2. Add a method to calculate yearly salary.
• 3. Create a class BankAccount with deposit and withdraw methods.
• 4. Create a class Mobile with brand and price properties.
This document is created for learning and portfolio purposes.