Learn JavaScript · lesson 44 of 60 · about 11 minutes
Project: Sam's Projects
Load Sam's coding projects from the server, handle failures, and sum them up with array methods.
What you'll learn
- Fetch and validate data
- Summarise it with map, filter and reduce
- Report results and failures cleanly
A projects panel
Sam keeps a list of coding projects on the server at /api/projects: each has a name, a number of stars from visitors and whether it's finished. The page loads them with the getJson helper from the guestbook, then sums them up in #projects: how many projects and stars there are, the most starred one, and the ones Sam is still building. If there are no projects it says No projects yet, and if the server is down it says Projects unavailable (HTTP 503) instead of crashing.
The plan
The explorer loads a list of courses from an API, then:
- counts the courses and total lessons
- finds the most popular course
- lists the beginner-friendly ones
If the API fails, it prints a friendly message instead of crashing.
The data explorer
// Pretend API so this runs offline
const COURSES = [
{ title: "Python", lessons: 60, learners: 5400, level: "beginner" },
{ title: "JavaScript", lessons: 60, learners: 6100, level: "beginner" },
{ title: "Rust", lessons: 40, learners: 900, level: "advanced" },
];
const fetch = async (url) =>
url.includes("/courses")
? new Response(JSON.stringify(COURSES), { status: 200 })
: new Response("", { status: 503 });
async function loadCourses(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`API returned ${res.status}`);
return res.json();
}
async function explore(url) {
try {
const courses = await loadCourses(url);
const lessons = courses.reduce((sum, c) => sum + c.lessons, 0);
const top = [...courses].sort((a, b) => b.learners - a.learners)[0];
const easy = courses.filter((c) => c.level === "beginner").map((c) => c.title);
console.log(`${courses.length} courses, ${lessons} lessons`);
console.log(`Most popular: ${top.title} (${top.learners.toLocaleString("en-GB")} learners)`);
console.log(`Beginner-friendly: ${easy.join(", ")}`);
} catch (err) {
console.log(`Sorry, couldn't load data (${err.message})`);
}
}
await explore("https://api.example.com/courses");
await explore("https://api.example.com/broken");Output
3 courses, 160 lessons
Most popular: JavaScript (6,100 learners)
Beginner-friendly: Python, JavaScript
Sorry, couldn't load data (API returned 503)Tip
In a module you can use await at the top level, outside any function, as the last two lines do.
Empty answers
A server can answer ok with an empty list. reduce with a starting value copes (the total is 0), and filter gives an empty list, but there's no first item after sorting: [...items].sort(...)[0] is undefined, and reading .name from it throws. So check for an empty list before you look for the top one.
Nothing to sum up
const items = [];
console.log(items.reduce((sum, i) => sum + i.stars, 0));
const [top] = [...items].sort((a, b) => b.stars - a.stars);
console.log(top);
console.log(items.length === 0 ? "Nothing yet" : top.name);Output
0
undefined
Nothing yetNow try it yourself
This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.