Course curriculum
JavaScript · LESSON 5 OF 5

Build a study-session summary

Write reusable functions and combine arrays, conditions and return values in a small project.

About 12 minutes · Beginner

Return a useful value

A function receives arguments through parameters. return ends the function and sends a value to the caller.

Keep calculation separate from display. Returning a number lets the caller log it, show it in a page or use it in another calculation.

JavaScript
function remaining(total, completed) {
  return Math.max(0, total - completed);
}
console.log(remaining(5, 2));
Expected output
3

Summarize sessions

This function accepts an array of study durations in minutes. It validates each value, totals the durations and returns an object describing the result.

An empty array is valid: it represents no sessions. A negative or non-finite duration is invalid and produces an error rather than an incorrect total.

JavaScript
function summarizeSessions(minutes) {
  let total = 0;
  for (const value of minutes) {
    if (!Number.isFinite(value) || value < 0) {
      throw new Error("Use non-negative minute values");
    }
    total += value;
  }
  return { sessions: minutes.length, totalMinutes: total };
}
const summary = summarizeSessions([25, 30, 20]);
console.log(`${summary.sessions} sessions: ${summary.totalMinutes} minutes`);
Expected output
3 sessions: 75 minutes

Plan the next improvement

Test the function with an empty array, a single session and an invalid negative duration. Keep these cases when you change the implementation.

A future interface could collect durations through a form. Validate those inputs and display error messages; do not hide failures or silently discard invalid sessions.

Try it yourself

Use summarizeSessions with [15, 45]. Then call it with [] and inspect totalMinutes.

Show a possible solution
JavaScript
console.log(summarizeSessions([15, 45]).totalMinutes); // 60
console.log(summarizeSessions([]).totalMinutes); // 0

Keep exploring: official JavaScript documentation.

0 of 5 completed on this device