You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// 12. Write a JavaScript program that creates a class called University with properties for university name and departments. Include methods to add a department, remove a department, and display all departments. Create an instance of the University class and add and remove departments.
2
+
3
+
classUniversity{
4
+
constructor(uni_name,departments){
5
+
this.uni_name=uni_name;
6
+
this.departments=[];
7
+
8
+
}
9
+
addDepartment(department){
10
+
this.departments.push(department);
11
+
console.log(`Department "${department}" added to ${this.name}.`);
12
+
}
13
+
removeDepartment(department){
14
+
constindex=this.departments.indexOf(department);
15
+
if(index!==-1){
16
+
this.departments.splice(index,1);
17
+
console.log(`Department "${department}" removed from ${this.name}.`);
18
+
}else{
19
+
console.log(`Department "${department}" does not exist in ${this.name}.`);
20
+
}
21
+
22
+
}
23
+
display(){
24
+
console.log(`Departments in ${this.uni_name}:`);
25
+
if(this.departments.length===0){
26
+
console.log('No departments available.');
27
+
}else{
28
+
this.departments.forEach((department,index)=>{
29
+
console.log(`${index+1}. ${department}`);
30
+
});
31
+
}
32
+
33
+
}
34
+
}
35
+
// Create an instance of the University class
36
+
constuniversity=newUniversity('ABC University');
37
+
// Perform operations on the university
38
+
university.display();// Departments in ABC University: No departments available.
39
+
40
+
university.addDepartment('Science');
41
+
university.addDepartment('Mathematics');
42
+
university.addDepartment('Physics');
43
+
university.display();
44
+
// Departments in ABC University:
45
+
// 1. Computer Science
46
+
// 2. Mathematics
47
+
// 3. Physics
48
+
49
+
university.removeDepartment('Mathematics');
50
+
university.display();
51
+
// Departments in ABC University:
52
+
// 1. Science
53
+
// 2. Physics
54
+
55
+
university.removeDepartment('Chemistry');
56
+
// Department "Chemistry" does not exist in ABC University
0 commit comments