AI Hints
Home›JavaScript Tutorial›Practice Projects 3
JavaScript · Lesson 121 of 138

Practice: Weather Report

Fetch and format.

⏱ 2 min read▶ Video at 2:25:23🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Most apps get their data from an API, a server that answers with JSON. Let's fetch a week of weather data, then turn it into a readable report, with the warmest day, the average, and the rainy days.

Practice: Weather Report
From the video: Practice: Weather Report
  • Data from an API
  • A week of weather
  • A readable report

Fetch, then summarise

Our tiny local server plays the part of a weather API. We fetch the forecast and read the JSON. Then plain array methods do the rest. Reduce finds the warmest day, map and reduce give the average, and filter finds the rainy days. Run it.

app.mjsjavascript
import http from "node:http";
const week = [["Mon", 18, 0], ["Tue", 21, 2], ["Wed", 24, 0], ["Thu", 19, 6],
  ["Fri", 16, 9], ["Sat", 22, 0], ["Sun", 23, 1]]
  .map(([day, temp, rain]) => ({ day, temp, rain }));
const server = http.createServer((q, r) => r.end(JSON.stringify(week))).listen(3003);

const days = await (await fetch("http://localhost:3003/forecast")).json();
server.close();

const warmest = days.reduce((a, b) => (b.temp > a.temp ? b : a));
const avg = days.map(d => d.temp).reduce((a, b) => a + b) / days.length;
const rainy = days.filter(d => d.rain > 0).map(d => d.day);

console.log(`Warmest: ${warmest.day} at ${warmest.temp}°C`);
console.log(`Average: ${avg.toFixed(1)}°C`);
console.log(`Rain on: ${rainy.join(", ")}`);
Output
Warmest: Wed at 24°C
Average: 20.4°C
Rain on: Tue, Thu, Fri, Sun

The shape of most apps

Nearly every app follows these steps. Fetch the data. Check that it arrived. Transform it with map, filter, and reduce. Then display it, in the console, or on a page. Once you're comfortable with these steps, you can build dashboards, reports, and tools from any API.

keyvalue
1. Fetchget the JSON
2. Checkres.ok, errors
3. Transformmap, filter, reduce
4. Displayconsole or page

Summary

Fetch, then transform with array methods, then display. That's the shape of most data apps. Next, a search box that waits for you to stop typing.

Key takeaways
  • fetch + json()
  • reduce for the max
  • filter + map
Next up: Practice: Debounced Search — wait for a pause