Emmanuel Akinfulubi

JavaScriptBasic

Calculate a weighted average grade in JavaScript

Intermediate · 4 min read

At most schools and universities, not every piece of work counts the same. Assignments might be worth 20% of the final mark, a midterm 30% and the exam 50%. To work out the final mark you need a weighted average, and getting it wrong can change a student's letter grade.

In this tutorial you will write weighted, which calculates a weighted mark from a list of scores and weights, and letter, which turns that mark into a grade. Then you'll compare the result with a plain average and see the two disagree by a whole letter. You need to know what arrays, objects and functions are. reduce is explained below.

Plain average versus weighted average

A plain average adds the scores and divides by how many there are. Every score counts equally.

A weighted average multiplies each score by its weight, adds those up, and divides by the total of the weights. Bigger weights pull the result toward their scores.

With scores of 90, 80 and 55 and weights of 20, 30 and 50:

Output

plain:    (90 + 80 + 55) / 3                  = 75
weighted: (90×20 + 80×30 + 55×50) / (20+30+50) = 6950 / 100 = 69.5

The exam counts for half the grade, and it was the lowest score, so the weighted mark is lower.

Adding up a list with reduce

reduce walks through an array and carries a running total along. You give it a function and a starting value:

JavaScript

const total = [90, 80, 55].reduce((sum, n) => sum + n, 0);
console.log(total); // 225

sum starts at 0. For each item n, the function returns sum + n, and that becomes the new sum.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

120 A weighted grade, and the average that lies

fair

Work out a final mark from assignments at 20%, a midterm at 30% and an exam at 50%, then turn it into a letter. Compare it with the plain average of the same three scores.

Stuck? Three hints, smallest first
  1. 1. Multiply each score by its weight, add them up, then divide by the total weight.
  2. 2. Dividing by the total weight means the weights can be 20/30/50 or 0.2/0.3/0.5 or 1/3/5.
  3. 3. A ladder of ifs for the letter must run from the highest threshold down.

Step 1: describe the scheme as data

Step 1

const SCHEME = [
  { name: 'assignments', weight: 20, score: 90 },
  { name: 'midterm', weight: 30, score: 80 },
  { name: 'exam', weight: 50, score: 55 },
];
console.log(SCHEME.length); // 3

Each part of the course is an object with a name, a weight and a score. Keeping them together in one array means the code doesn't need to know how many parts there are.

Step 2: the weighted mark

Step 2

const SCHEME = [
  { name: 'assignments', weight: 20, score: 90 },
  { name: 'midterm', weight: 30, score: 80 },
  { name: 'exam', weight: 50, score: 55 },
];
function weighted(parts) {
  const totalWeight = parts.reduce((sum, p) => sum + p.weight, 0);
  const points = parts.reduce((sum, p) => sum + p.score * p.weight, 0);
  return Math.round((points / totalWeight) * 10) / 10;
}
console.log(weighted(SCHEME)); // 69.5

The first reduce adds the weights (100). The second adds each score times its weight (6950). Dividing gives 69.5.

Math.round(x * 10) / 10 rounds to one decimal place: multiply by 10, round to a whole number, divide by 10 again.

Step 3: why divide by the total weight

You could divide by 100, since the weights add up to 100. Dividing by the total instead means the weights can be written any way you like:

Step 3

function weighted(parts) {
  const totalWeight = parts.reduce((sum, p) => sum + p.weight, 0);
  const points = parts.reduce((sum, p) => sum + p.score * p.weight, 0);
  return Math.round((points / totalWeight) * 10) / 10;
}
console.log(weighted([{ weight: 1, score: 100 }, { weight: 3, score: 60 }])); // 70
console.log(weighted([{ weight: 20, score: 90 }, { weight: 30, score: 80 }])); // 84

Weights of 1 and 3 work. And the second line drops the exam: the two remaining parts are reweighted automatically, rather than the missing exam being scored as zero. Weights written as fractions like 0.2, 0.3 and 0.5 give the same 69.5 too.

Step 4: an empty scheme

Step 4

console.log(0 / 0); // NaN

With no parts, both totals are 0, and 0 / 0 is NaN ("not a number"). NaN is sneaky: any sum with it gives NaN, and comparisons like >= with it are always false, so the problem spreads quietly. The function guards against it by returning 0 when the total weight is zero:

JavaScript

function weighted(parts) {
  const totalWeight = parts.reduce((sum, p) => sum + p.weight, 0);
  if (totalWeight === 0) return 0;
  const points = parts.reduce((sum, p) => sum + p.score * p.weight, 0);
  return Math.round((points / totalWeight) * 10) / 10;
}
console.log(weighted([])); // 0

Step 5: from a mark to a letter

Step 5

function letter(mark) {
  if (mark >= 70) return 'A';
  if (mark >= 60) return 'B';
  if (mark >= 50) return 'C';
  if (mark >= 45) return 'D';
  return 'F';
}
console.log(letter(69.5)); // B
console.log(letter(70));   // A
console.log(letter(69.9)); // B

Each if returns as soon as it's true, so the order matters. The checks run from the highest threshold down. If you wrote them from the bottom up, starting with mark >= 45, a mark of 90 would match that first and come back as a D.

The >= makes each band include its lower edge: exactly 70 is an A.

Step 6: the plain average lies

Step 6

const SCHEME = [
  { name: 'assignments', weight: 20, score: 90 },
  { name: 'midterm', weight: 30, score: 80 },
  { name: 'exam', weight: 50, score: 55 },
];
const plainAverage = (parts) =>
  Math.round((parts.reduce((sum, p) => sum + p.score, 0) / parts.length) * 10) / 10;
console.log(plainAverage(SCHEME)); // 75

75 is an A. The correct weighted mark, 69.5, is a B. A student who did well in coursework and badly in the exam would get the wrong grade from the wrong formula.

The full solution

The answer panel has weighted, letter and plainAverage, and prints both marks with their letters. The checks cover the weighted mark, its letter, the plain average's A, fractional weights, weights that don't total 100, dropping the exam, the band edges and the empty scheme. Press Run to see the output.

The answer

const SCHEME = [
  { name: 'assignments', weight: 20, score: 90 },
  { name: 'midterm', weight: 30, score: 80 },
  { name: 'exam', weight: 50, score: 55 },
];
function weighted(parts) {
  const totalWeight = parts.reduce((sum, p) => sum + p.weight, 0);
  if (totalWeight === 0) return 0;
  const points = parts.reduce((sum, p) => sum + p.score * p.weight, 0);
  return Math.round((points / totalWeight) * 10) / 10;
}
function letter(mark) {
  if (mark >= 70) return 'A';
  if (mark >= 60) return 'B';
  if (mark >= 50) return 'C';
  if (mark >= 45) return 'D';
  return 'F';
}
const plainAverage = (parts) =>
  Math.round((parts.reduce((sum, p) => sum + p.score, 0) / parts.length) * 10) / 10;
const asFractions = SCHEME.map((p) => ({ ...p, weight: p.weight / 100 }));
console.log('weighted', weighted(SCHEME), letter(weighted(SCHEME)), '/ unweighted', plainAverage(SCHEME), letter(plainAverage(SCHEME)));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the weighted mark', weighted(SCHEME), 69.5);
test('which is a B, by half a mark', letter(weighted(SCHEME)), 'B');
test('the plain average would have given an A', [plainAverage(SCHEME), letter(plainAverage(SCHEME))], [75, 'A']);
test('fractions as weights give the same answer', weighted(asFractions), 69.5);
test('so do weights that do not total a hundred', weighted([{ weight: 1, score: 100 }, { weight: 3, score: 60 }]), 70);
test('dropping the exam reweights what is left', weighted(SCHEME.slice(0, 2)), 84);
test('the threshold is inclusive at the bottom of each band', [letter(70), letter(69.9)], ['A', 'B']);
test('an empty scheme is zero, not NaN', weighted([]), 0);
test('which is what the division alone would have produced', Number.isNaN(0 / 0), true);

The gap between 69.5 and 75 is the exercise. Averaging the three scores treats a coursework mark as equal to an exam that is half the grade, and here that difference is a whole letter — the student who did well on assignments and badly in the exam gets an A from the wrong formula. Weight, then divide by the total weight.

Dividing by the total rather than by 100 is what makes the function reusable: 20/30/50, 0.2/0.3/0.5 and 1/3/5 all give 69.5, and a component that gets dropped reweights the rest automatically instead of quietly scoring the missing part as zero. The totalWeight === 0 guard matters because 0 / 0 is NaN, and NaN propagates silently through every later sum and comparison — the assertion pins that down rather than trusting it. The letter ladder must descend: written from the lowest threshold up, every passing mark would return the lowest letter, because the first true branch wins (exercise 91 on guard clauses is the same shape).

Common mistakes

  • Using a plain average. Every part counts the same, which isn't what the course says.
  • Dividing by 100 instead of the total weight. It breaks as soon as the weights don't add up to 100.
  • Ordering the grade checks from the bottom up. The first true if wins, so the highest threshold must come first.

Try it yourself

  1. Add a fourth part, a project worth 10, and change the other weights so the total is still 100.
  2. Write neededInExam(parts, target): what exam score does the student need for a final mark of 70?
  3. Change letter to read its bands from an array like [[70, 'A'], [60, 'B'], ...].

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.