Hi everyone. I did this “Grade” Exercise:
const marks = [80, 80, 50];
console.log(calculateGrade(marks));
function calculateGrade(marks) {
let sum = 0;
for (let mark of marks) sum += mark;
let average = sum / marks.length;
if (average < 60) return “F”;
if (average < 70) return “D”;
if (average < 80) return “C”;
if (average < 90) return “B”;
return “A”;
}
i understud everything exept this expression sum += mark.
I know that variable include three numbers collected from arrey. If i will console.log (mark) it will give me 80, 80, 50 - three sepparete numbers. If i will shift this expressoin sum += mark with anather aruthmetic expression like - mark + 1 it still gives me three sepparete number but in a case of sum += mark number are summing. Please explane me how does it happend or shere me a right article abaut this topic.
Thank you
function calculateGrade(marks) {
let sum = 0;
for (let mark of marks) {
sum += mark;
}
let average = sum / marks.length;
let grade = null;
if (average < 60) {
grade = "F";
} else if (average < 70) {
grade = "D";
} else if (average < 80) {
grade = "C";
} else if (average < 90) {
grade = "B";
} else {
grade = "A";
}
return grade;
}
const marks = [80, 80, 50];
console.log(calculateGrade(marks));
sum += mark
is the shorthand of sum = sum + mark
. You declared and initialized a variable let sum = 0
. Then, you are looping through the array, and taking the value at each index and adding it to sum for your total.
sum = 0
sum = sum + 80 (80 + 0 = 80)
sum = sum + 80 (80 + 80 = 160)
sum = sum + 50 (160+ 50 = 210)
sum = 210;