JS Classes

HTML
CSS
C#
SQL

Classes

ECMAScript 2015 (ES6) introduced the concept of classes in JavaScript. Classes serve as templates for creating objects, providing a structured way to define object blueprints.

Use the keyword class to create a class.
Always add a method named constructor():

Syntax:

class ClassName {
  constructor() { … }
}

Example:

     class Car {
       constructor(name, year) {
         this.name = name;
         this.year = year;
       }
     }

1. Using a Class:

Once a class is defined, instances (objects) can be created using the new keyword followed by the class name and any required parameters for the constructor.

Example:

     let myCar1 = new Car(“Ford”, 2014);
     let myCar2 = new Car(“Audi”, 2019);

2. Classes Properties:

JavaScript objects are collections of unordered properties. Properties can be accessed using dot notation, square brackets, or by storing the property name in a variable.

Example:

     var student = {
       name: “Chris Hemsworth”,
       age: 21,
       branch: “Computer Science”,
     };

     // Accessing properties
     student.age;          // Dot notation
     student[“age”];       // Square brackets
     let x = “age”;
     student[x];           // Using a variable

3. Classes Methods:

Class methods are created within a class using the same syntax as object methods. They define the behavior of instances created from the class.

Example:

4. Inheritance:

Inheritance allows a class to inherit methods from another class. In JavaScript, it is achieved using the extends keyword.

Example:

5. Super Keyword:

The super keyword is used in a subclass to call methods of its superclass. It is particularly useful when accessing variables, methods, or constructors in the base class from the derived class.

Example:

6. Static Methods:

Static methods are defined on the class itself, not on instances of the class. They are called on the class, not on objects.

Example:

7. Getters and Setters:

Getters and setters are methods used for getting and setting the values of properties. They ensure controlled access to object properties.

Example:

Course Video

Examples for Practice

You have to solve all the questions given below in the editor without copy-pasting.

1. Create a class Rectangle with properties of width and height. Add a method calculateArea that returns the area of the rectangle.

The task is to create a JavaScript class named Rectangle with two properties, width and height. Additionally, you need to add a method called calculateArea to the class, which calculates and returns the area of the rectangle.
1. Create the Rectangle Class:
Define a class called Rectangle using the class keyword.
2. Add Properties:
Inside the class, add two properties, width and height, to represent the dimensions of the rectangle. You can do this within the class constructor.
3. Add the calculateArea Method:
Still inside the class, add a method called calculateArea that calculates the area of the rectangle using the formula: area = width * height.

Here’s an example program:

class Rectangle {
// Step 2: Add properties (width and height) within the constructor
constructor(width, height) {
this.width = width;
this.height = height;
}

// Step 3: Add the calculateArea method
calculateArea() {
// Calculate and return the area of the rectangle
return this.width * this.height;
}
}

// Example usage:
// Create an instance of the Rectangle class with width 5 and height 10
const myRectangle = new Rectangle(5, 10);

// Call the calculateArea method to get the area
const area = myRectangle.calculateArea();

// Display the result
console.log(“Area of the rectangle:”, area);

Output

2. Write a JS program to Calculate the area of a square using inheritance by taking the side from the user.

The task is to write a JavaScript program that calculates the area of a square using inheritance. In this context, inheritance means creating a class that inherits properties or methods from another class.
1. Create a Base Class (Shape):
Define a base class called Shape (or any suitable name) that has a property or method to calculate the area.
2. Create a Derived Class (Square):
– Create a derived class called Square that inherits from the Shape class.
– The Square class should have a property to represent the side length of the square.
3. Calculate Area:
Add a method to the Square class to calculate the area of the square based on its side length.
4. User Input:
Prompt the user to enter the side length of the square.

Here’s an example program:

// Step 1: Create a Base Class (Shape)
class Shape {
// The base class can have common properties or methods related to shapes
}

// Step 2: Create a Derived Class (Square) that inherits from Shape
class Square extends Shape {
// Step 3: Add a property for side length
constructor(sideLength) {
super(); // Call the constructor of the base class
this.sideLength = sideLength;
}

// Step 3: Add a method to calculate the area of the square
calculateArea() {
return this.sideLength * this.sideLength;
}
}

// Step 4: User Input
// Prompt the user to enter the side length of the square
var side = parseFloat(prompt(“Enter the side length of the square:”));

// Check if the user entered a valid number
if (!isNaN(side) && side > 0) {
// Step 5: Example Usage
// Create an instance of the Square class with the user-provided side length
const userSquare = new Square(side);

// Calculate and display the area
const area = userSquare.calculateArea();
console.log(`The area of the square with side length ${side} is: ${area}`);
} else {
console.log(“Invalid input. Please enter a valid positive number for the side length.”);
}

 

Output

3. Write a JS program to calculate the Average of the total marks using class Methods.

The task is to write a JavaScript program that calculates the average of total marks using class methods.
1. Create a Class:
Define a class, let’s call it StudentMarks or any suitable name.
2. Add Properties:
Add properties to the class to represent the total marks obtained by a student. You might also include the number of subjects or any other relevant information.
3. Add a Method to Enter Marks:
Add a method to the class that allows the user to enter marks for each subject. This method should update the total marks property.
4. Add a Method to Calculate Average:
Add another method to the class that calculates and returns the average of the total marks.
5. User Input:
Prompt the user to enter marks for each subject.

Here’s an example program:

// Step 1: Create a Class (StudentMarks)
class StudentMarks {
// Step 2: Add properties (totalMarks, numOfSubjects, etc.)
constructor() {
this.totalMarks = 0;
this.numOfSubjects = 0;
}

// Step 3: Add a method to enter marks for each subject
enterMarks(subjectMarks) {
this.totalMarks += subjectMarks;
this.numOfSubjects++;
}

// Step 4: Add a method to calculate the average
calculateAverage() {
// Check if there are subjects to avoid division by zero
if (this.numOfSubjects > 0) {
return this.totalMarks / this.numOfSubjects;
} else {
return 0; // Avoid division by zero
}
}
}

// Step 5: User Input
// Prompt the user to enter marks for each subject
var marks1 = parseFloat(prompt(“Enter marks for subject 1:”));
var marks2 = parseFloat(prompt(“Enter marks for subject 2:”));
// Continue this for other subjects as needed

// Step 6: Example Usage
// Create an instance of the StudentMarks class
const student = new StudentMarks();

// Enter marks for each subject
student.enterMarks(marks1);
student.enterMarks(marks2);
// Continue this for other subjects as needed

// Calculate and display the average
const average = student.calculateAverage();
console.log(`The average of total marks is: ${average}`);

Output

4. Write a JS program to print the names of Different Students and the Average of all marks by taking Marks as an array.

The task is to write a JavaScript program that prints the names of different students along with their average marks. The marks will be provided as an array for each student.
1. Create a Class:
Define a class, let’s call it Student or any suitable name.
2. Add Properties:
Add properties to the class to represent the student’s name and marks.
3. Add a Method to Calculate Average:
Add a method to the class that calculates and returns the average of the marks.
4. Create Instances for Different Students:
Create instances of the Student class for different students, providing their names and marks as arrays.
5. Display Information:
Display the names of the students along with their average marks.

Here’s an example program:

// Step 1: Create a Class (Student)
class Student {
// Step 2: Add properties (name, marks)
constructor(name, marks) {
this.name = name;
this.marks = marks;
}

// Step 3: Add a method to calculate the average
calculateAverage() {
if (this.marks.length > 0) {
const sum = this.marks.reduce((total, mark) => total + mark, 0);
return sum / this.marks.length;
} else {
return 0; // Avoid division by zero
}
}
}

// Step 4: Create Instances for Different Students
const student1 = new Student(“Alice”, [80, 75, 90]);
const student2 = new Student(“Bob”, [85, 92, 88]);
const student3 = new Student(“Charlie”, [78, 80, 85]);

// Step 5: Display Information
console.log(`${student1.name}’s average marks: ${student1.calculateAverage()}`);
console.log(`${student2.name}’s average marks: ${student2.calculateAverage()}`);
console.log(`${student3.name}’s average marks: ${student3.calculateAverage()}`);

Output

5. Create a class BankAccount with properties balance and owner. Add methods of deposit and withdrawal to update the balance.

The task is to create a JavaScript class named BankAccount with two properties, balance and owner. Additionally, you need to add two methods, deposit and withdrawal, to the class. These methods will be responsible for updating the balance when money is deposited or withdrawn from the bank account.
1. Create the BankAccount Class:
Define a class called BankAccount using the class keyword.
2. Add Properties: Inside the class, add two properties, balance and owner, to represent the account’s balance and owner’s name.
3. Add the deposit Method:
Add a method called deposit that takes an amount as a parameter and updates the balance by adding the deposited amount.
4. Add the withdrawal Method:
Add a method called withdrawal that takes an amount as a parameter and updates the balance by subtracting the withdrawn amount.

Here’s an example program:

class BankAccount {
// Step 2: Add properties (balance and owner)
constructor(balance, owner) {
this.balance = balance;
this.owner = owner;
}

// Step 3: Add the deposit method
deposit(amount) {
// Update the balance by adding the deposited amount
this.balance += amount;
console.log(`Deposited ${amount} into ${this.owner}’s account. New balance: ${this.balance}`);
}

// Step 4: Add the withdrawal method
withdrawal(amount) {
// Check if there is sufficient balance before withdrawing
if (amount <= this.balance) {
// Update the balance by subtracting the withdrawn amount
this.balance -= amount;
console.log(`Withdrawn ${amount} from ${this.owner}’s account. New balance: ${this.balance}`);
} else {
console.log(`Insufficient funds for withdrawal from ${this.owner}’s account.`);
}
}
}

// Example usage:
// Create an instance of the BankAccount class with initial balance 1000 and owner’s name “John”
const johnsAccount = new BankAccount(1000, “John”);

// Deposit 500 into John’s account
johnsAccount.deposit(500);

// Withdraw 200 from John’s account
johnsAccount.withdrawal(200);

// Attempt to withdraw 1000 (more than the balance) from John’s account
johnsAccount.withdrawal(1000);

Output