Curly braces changes sum output of Array

Difficult to make a meaningful post title, what I mean is I am doing a for…of exercise finding the average of an array.

This version works…

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';

}

but this version (where I left unnecessary curly braces in) returns ‘F’ and I can’t figure out why. I know I can just remove the braces but I am curious why it gives a wrong answer as opposed to just an error. Any advice greatly appreciated.

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';

}

}

(read how to properly format code here)

The syntax of “for of” is

for (variable of iterable) statement-to-execute;

statement-to-execute can be a single statement or a codeblock in curly braces that can contain multiple statements.

So the first version is executed as your indentation suggests: for every mark in marks mark is added to sum and afterwards the average is calculated and the respective grade is returned.

With the curly braces in the second example you say that you want the whole code block in braces to be executed for each iteration. So in the first iteration you add 80 to sum calculate an average of 80 / 3 (a little less than 27) and return the respective grade of “F”. And since you already returned a value there will be no second and third iteration.

1 Like

So because it includes whole block, it gets to the return having only gone 1 loop and so the first mark (80) is divided by 3 and an ‘F’ is returned.

Awesome, thankyou very much Sam.