🟨 JavaScript tutorial for beginners · Class 9 · Lesson 18 of 18 · Free
Capstone: Weather Dashboard – A Full JavaScript App with an API
⏱ About 45 minutes · ▶ run real JavaScript here — nothing to install · no sign-in
In this lesson you will
- Plan an app and build it in small, tested steps
- Fetch, check and show API data with loading and error messages
- Add a forecast, remembered city and a city comparison
Your family is planning a winter trip: Shimla or Jaipur? Will it snow, will it rain? Today you build a weather dashboard that answers in one click. It uses almost everything from this course: fetch, async/await, error handling, state, events, the DOM and localStorage.
What will our JavaScript weather dashboard do?
Good apps start with a plan. Ours: (1) the user types or picks a city, (2) we fetch its weather, (3) we show a card and a 3-day forecast, (4) we show a clear message for unknown cities, (5) we remember the last city.
Our data comes from the TalentJR practice API. The weather is made up, so it is the same every time — perfect for practice. No API key is needed.
First step: look at the data before writing any page code. Which fields will the card need?
Cities: ["Pune", "Mumbai", "Delhi", "Chennai", "Kolkata", "Bengaluru", "Jaipur", "Shimla"]{ city: "Pune", temp_c: 24, condition: "Sunny", humidity: 40, wind_kmh: 12, forecast: [{ day: "Mon", high: 29, low: 17, condition: "Sunny" }, { day: "Tue", high: 30, low: 18, condition: "Cloudy" }, { day: "Wed", high: 28, low: 17, condition: "Sunny" }], note: "Practice data for TalentJR coding lessons — made up, not real weather." }Fields: ["city", "temp_c", "condition", "humidity", "wind_kmh", "forecast", "note"]
💡 Try it: change Pune to Shimla and look at the forecast array.
How do I turn weather data into friendly text?
Raw data like `condition: "Rain"` is fine for computers. People like 🌧️ and short sentences. Small helper functions do this formatting.
An object works as a lookup table: `icons["Rain"]` gives 🌧️. The `||` gives a default icon for any condition we did not list.
These helpers take plain data and return text — no fetch, no DOM — so they are easy to test (Lesson 17). The trace uses a fixed sample day.
▶const icons = { Sunny: "☀️", Cloudy: "☁️", Rain: "🌧️", Snow: "❄️", Foggy: "🌫️" };23function iconFor(condition) {4 return icons[condition] || "🌡️";5}67function dayText(day) {8 return `${day.day}: ${iconFor(day.condition)} ${day.low}–${day.high}°C`;9}1011const sample = [12 { day: "Mon", high: 8, low: 2, condition: "Snow" },13 { day: "Tue", high: 9, low: 3, condition: "Humid" }14];15console.log(sample.map(dayText));
No variables yet.
▌✏️ Change this code and run it yourself
["Mon: ❄️ 2–8°C", "Tue: 🌡️ 3–9°C"]
💡 Humid is not in the icons table, so it gets the default 🌡️. Try it: add Humid: "💧" to icons.
How do I fetch weather safely in JavaScript?
Users type messy things: " shimla ", "Goa", or nothing at all. Our `getWeather` function cleans the input with `trim()`, refuses an empty name, and checks `res.ok` (Lesson 14).
`encodeURIComponent` makes a name with spaces safe inside a URL.
Whatever goes wrong, `getWeather` throws an Error with a message we can show. The caller decides how to show it.
▶const API = "https://api.talentjr.in/api/v1/practice";23async function getWeather(city) {4 const name = city.trim();5 if (!name) throw new Error("Please type a city name");6 const res = await fetch(`${API}/weather?city=${encodeURIComponent(name)}`);7 const data = await res.json();8 if (!res.ok) throw new Error(`${data.error}: ${name}`);9 return data;10}1112for (const city of [" shimla ", "Goa", ""]) {13 try {14 const w = await getWeather(city);15 console.log(`${w.city}: ${w.temp_c}°C, ${w.condition}`);16 } catch (err) {17 console.log("⚠️", err.message);18 }19}
No variables yet.
▌✏️ Change this code and run it yourself
Shimla: 4°C, Snow⚠️ City not found: Goa⚠️ Please type a city name
💡 The practice API ignores capital letters, so "shimla" works. Try it: add "New Delhi" to the list.
How do I show the weather on a web page?
Now the first real dashboard: a form, a status line and a card. The flow is the same as Lesson 14: show "Loading…", await the data, then fill the card — or show the error.
We use a form `submit` event, so pressing Enter works too. `e.preventDefault()` stops the browser from reloading the page.
Type a city and press Enter. Try "Ooty" to see the error message.
📄 HTML of the page (tap to see / edit)
Showing Mumbai 31
💡 Try it: show "Feels hot!" in the card when temp_c is 30 or more.
How do I add a forecast and remember the last city?
The full dashboard adds three things: quick buttons for every city (made from `/weather/cities`), a 3-day forecast row, and `localStorage` to remember the last city (Class 8 Lesson 13).
It follows Lesson 15: one `state` object, and a `render()` that draws everything from it. Clicks only change the city and call `load()`.
The city buttons use event delegation from Lesson 16: one listener for all of them.
📄 HTML of the page (tap to see / edit)
Now showing Pune | forecast: 29, 30, 28
💡 Click a city, then press ▶ Run again: the dashboard opens on the city you picked last (so your output may differ from the first run).
How do I compare the weather of many cities at once?
Trip planning question: which city is warmest, and which is coldest? We need ALL cities, so we fetch them together with `Promise.all` (Lesson 13) — much faster than one by one.
Then plain array skills from Lesson 2: `sort` by temperature and pick the first and last.
`[...all]` copies the array first, so sorting does not change the original order.
Mumbai 31°C HumidChennai 29°C CloudyPune 24°C SunnyKolkata 22°C SunnyBengaluru 21°C CloudyJaipur 18°C SunnyDelhi 14°C FoggyShimla 4°C SnowWarmest: Mumbai | Coldest: Shimla
💡 Try it: also print the most humid city (sort by humidity).
🤔 Predict the output
Think like JavaScript: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
const icons = { Sunny: "☀️", Rain: "🌧️" };
console.log(icons["Snow"] || "🌡️", icons.Rain);Question 2. What does this print?
const temps = [24, 4, 31, 18]; const sorted = [...temps].sort((a, b) => b - a); console.log(sorted[0], temps[0]);
Question 3. What does this print?
async function getTemp() {
return 24;
}
const t = getTemp();
console.log("Pune: " + t + "°C");🧩 Your challenge
Winter trip planner: for the cities ["Shimla", "Chennai", "Jaipur", "Goa"], fetch the weather TOGETHER, and print a tip for each: below 10°C → "wear a sweater", 30°C or more → "carry water", else "perfect weather". An unknown city prints "not found" and must not crash the others. Finish with the warmest found city. Expected output: Shimla: 4°C – wear a sweater Chennai: 29°C – perfect weather Jaipur: 18°C – perfect weather Goa: not found Warmest: Chennai
Shimla: 4°C – wear a sweater Chennai: 29°C – perfect weather Jaipur: 18°C – perfect weather Goa: not found Warmest: Chennai
⚠️ Common mistakes (and how to fix them)
❌ Wrong
const API = "https://api.talentjr.in/api/v1/practice";
const res = await fetch(`${API}/weather?city=Ooty`);
const data = await res.json();
console.log(data.forecast.map((d) => d.high));TypeError: Cannot read properties of undefined (reading 'map')
✅ Right
const API = "https://api.talentjr.in/api/v1/practice";
const res = await fetch(`${API}/weather?city=Ooty`);
const data = await res.json();
if (!res.ok) console.log("⚠️", data.error);
else console.log(data.forecast.map((d) => d.high));For an unknown city the server sends { error: "City not found" }, which has no forecast. Check res.ok before you use the data.
❌ Wrong
document.querySelector("#search").addEventListener("submit", () => {
const city = document.querySelector("#city").value;
document.querySelector("#out").textContent = "Searching " + city;
});
console.log("Ready");No error, but when you press Search the page reloads — "Searching Delhi" flashes for a moment and is gone.
✅ Right
document.querySelector("#search").addEventListener("submit", (e) => {
e.preventDefault();
const city = document.querySelector("#city").value;
document.querySelector("#out").textContent = "Searching " + city;
});
console.log("Ready");A form's normal job is to send the page away and reload. e.preventDefault() stops that so your JavaScript can do the work.
❌ Wrong
const API = "https://api.talentjr.in/api/v1/practice";
async function getTemp(city) {
const data = await (await fetch(`${API}/weather?city=${city}`)).json();
return data.temp_c;
}
console.log("Pune is " + getTemp("Pune") + "°C");No error, but it prints "Pune is [object Promise]°C" instead of the temperature.
✅ Right
const API = "https://api.talentjr.in/api/v1/practice";
async function getTemp(city) {
const data = await (await fetch(`${API}/weather?city=${city}`)).json();
return data.temp_c;
}
console.log("Pune is " + (await getTemp("Pune")) + "°C");Every async function returns a Promise. You must await it to get the number.
📌 Remember
- Plan first, look at the data, then build in small steps that each work.
- One careful getWeather() cleans the input, checks res.ok and throws clear errors.
- Show "Loading…", then the card or a friendly error — the page never freezes.
- Keep data in state, draw it with render(), remember choices with localStorage.
- Promise.all + sort answers big questions, like the warmest city, in one go.
Finished the quiz and the challenge?
Questions students ask
How do I make a weather app in JavaScript?
You need three parts: an HTML form for the city, a fetch call to a weather API with async/await, and DOM code to show the result. This lesson builds all three step by step with a free practice API, so you can start without any sign-up.
Can I use real weather data instead of the practice API?
Yes. Services like OpenWeatherMap give real data, but you must sign up for an API key, and the field names are different (for example main.temp in Kelvin). Change getWeather() to read the new fields — the rest of your dashboard stays the same.
Why does my weather app show undefined?
Usually one of three reasons: you forgot await, the city was not found (check res.ok), or you used a wrong field name. console.log the whole data object to see the real field names.
What can I add to my weather dashboard next?
Ideas: a °C/°F switch, a background colour that changes with the weather, a list of favourite cities saved in localStorage, or a small chart of the 3-day forecast. Each one uses skills from this course.