Before this lesson
Understand variables, Booleans, comparisons and type conversion.
What you will be able to do
Translate rules into mutually exclusive branches and test loops for missing or repeated work.
Understand the mechanism
if selects the first matching branch, so put the most restrictive range first. Logical AND and OR short-circuit and return an operand, not necessarily a boolean. Nullish coalescing supplies a default only for null or undefined, preserving zero and empty strings.
Use for for indexed control and for...of for iterable values. Array indexes start at zero and normally stop before length. continue skips the remainder of one iteration; break ends the current loop, not every enclosing loop.
Reason about initialization, an invariant and termination. While summing scores, sum should equal the total of valid scores already processed. Keep filtering and accumulation clear. Handle empty collections before division.
Runnable example
const scores = [0, 60, 85, 100, -1];
let sum = 0;
let count = 0;
for (const score of scores) {
if (!Number.isFinite(score) || score < 0 || score > 100) continue;
sum += score;
count += 1;
}
const average = count === 0 ? null : sum / count;
console.log({ sum, count, average });
Trace and verify
Expect total 245, four valid entries and average 61.25. An empty array produces null; the string 60 is excluded. Track score, sum and count on paper before comparing the console.
Common mistakes and boundaries
A while loop that never updates its controlling state can freeze a page. Do not suppress all exceptions to keep execution going. Invalid user input is often an ordinary branch, not an exception.
Practice challenge
Add grades: A from 90, B from 60, otherwise C; show Unrated when no valid score exists. Test 59.99, 60, 89.99 and 90.
Reference solution and reasoning
Handle null first, then evaluate ranges from highest to lowest. Testing >=60 first incorrectly captures scores of 90 before the A branch.
function grade(n) {
if (n === null) return "Unrated";
if (n >= 90) return "A";
if (n >= 60) return "B";
return "C";
}