EXERCISE 5: Student Information - Solution Code

← Back to Assignment

Solution Files

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exercise 5 - Student Information</title>
</head>
<body>
    <h1>Exercise 5: Student Information</h1>

    <script src="script.js"></script>
</body>
</html>
script.js
// Create student object
const student = {
    name: 'Alice Johnson',
    age: 20,
    courses: ['JavaScript', 'HTML', 'CSS'],
    grade: {
        'JavaScript': 85,
        'HTML': 92,
        'CSS': 88
    },
    isActive: true
};

// Function to get student info
function getStudentInfo(student) {
    return `
        <strong>Name:</strong> ${student.name}<br>
        <strong>Age:</strong> ${student.age}<br>
        <strong>Courses:</strong> ${student.courses.join(', ')}<br>
        <strong>Active:</strong> ${student.isActive ? 'Yes' : 'No'}
    `;
}

// Function to calculate average grade
function calculateAverage(student) {
    let total = 0;
    let count = 0;

    for (let course in student.grade) {
        total += student.grade[course];
        count++;
    }

    return count > 0 ? total / count : 0;
}

// Display student information
document.write("<h2>Student Information:</h2>");
document.write(getStudentInfo(student));

// Display grades using for...in loop
document.write("<h2>Grades:</h2><ul>");
for (let course in student.grade) {
    document.write(`<li>${course}: ${student.grade[course]}%</li>`);
}
document.write("</ul>");

// Display average grade
const average = calculateAverage(student);
document.write(`<p><strong>Average Grade: ${average.toFixed(2)}%</strong></p>`);