You will build a simple application where a user enters student details and the system calculates grades automatically.
The app should:
<input id="name" placeholder="Enter name">
<input id="marks" placeholder="Enter marks">
<button onclick="addStudent()">Add Student</button>
<div id="output"></div>
let name = document.getElementById("name").value;
let marks = document.getElementById("marks").value;
class Student {
constructor(name, marks) {
this.name = name;
this.marks = marks;
}
}
getGrade() {
if (this.marks >= 80) return "A";
else if (this.marks >= 60) return "B";
else if (this.marks >= 40) return "C";
else return "Fail";
}
let students = [];
function addStudent() {
let name = document.getElementById("name").value;
let marks = Number(document.getElementById("marks").value);let student = new Student(name, marks); students.push(student);
displayStudents(); }
for (let i = 0; i < students.length; i++) {
console.log(students[i]);
}
let s1 = new Student("Ali", 75);
let s2 = new Student("Sara", 85);
students.push(s1);
students.push(s2);
class GraduateStudent extends Student {
constructor(name, marks, thesisTitle) {
super(name, marks);
this.thesisTitle = thesisTitle;
}
}
class Student {
static count = 0;constructor(name, marks) { this.name = name; this.marks = marks; Student.count++; }
static getCount() { return Student.count; } }
document.getElementById("output").innerHTML +=
student.name + " got " + student.getGrade();
This is the full working example. Use it to compare with your own work after trying.
class Student {
static count = 0;constructor(name, marks) { this.name = name; this.marks = marks; Student.count++; }
getGrade() { if (this.marks >= 80) return "A"; else if (this.marks >= 60) return "B"; else if (this.marks >= 40) return "C"; else return "Fail"; }
static getCount() { return Student.count; } }
class GraduateStudent extends Student { constructor(name, marks, thesisTitle) { super(name, marks); this.thesisTitle = thesisTitle; } }
let students = [];
function addStudent() { let name = document.getElementById("name").value; let marks = Number(document.getElementById("marks").value);
let student = new Student(name, marks); students.push(student);
displayStudents(); }
function displayStudents() { let output = document.getElementById("output"); output.innerHTML = "";
for (let i = 0; i < students.length; i++) { let s = students[i]; output.innerHTML += s.name + " got grade " + s.getGrade() + "
"; }
output.innerHTML += "
Total Students: " + Student.getCount(); }