Weather App in JavaScript
Display sample weather in JavaScript with an async function and field checks. The default uses local Pune data, not live forecasts or a working API endpoint.
Save this as index.html and open it in a browser.
1<!doctype html>2<html lang="en">3<meta charset="utf-8">4<title>JavaScript practice</title>5<body>6<button id="load">Show sample weather</button><p id="weather">No weather loaded.</p>7<script>8// Sample data, not live weather. No API key is needed.9const sample = { city: 'Pune', tempC: 27, condition: 'Cloudy' };10async function getWeather(useMock = true) {11 if (useMock) return { ...sample };12 // Replace this placeholder with your own permitted endpoint before using false.13 const response = await fetch('https://weather.example.invalid/current?city=Pune');14 if (!response.ok) throw new Error('Weather request failed: ' + response.status);15 return response.json();16}17document.querySelector('#load').onclick = async () => {18 const output = document.querySelector('#weather'); output.textContent = 'Loading sample...';19 try {20 const data = await getWeather();21 if (typeof data.city !== 'string' || !Number.isFinite(data.tempC) || typeof data.condition !== 'string') throw new Error('Unexpected weather data');22 output.textContent = data.city + ': ' + data.tempC + ' °C, ' + data.condition + ' (sample)';23 } catch (error) { output.textContent = 'Could not load weather: ' + error.message; }24};25</script>26</body>27</html>
Sample Output
Pune: 27 °C, Cloudy (sample)
The default loader returns a fixed object. No current weather service was called.
In this one
- Display clearly labelled sample weather
- Wait for a data-loading function
- Validate incoming fields
- Recognize placeholder endpoints and CORS limits
How it works
- 1
Start with a fixed sample object in Celsius.
- 2
Call getWeather with its default mock mode after the click.
- 3
Show a loading message while awaiting the result.
- 4
Check city, tempC, and condition before building text.
- 5
Display Pune: 27 °C, Cloudy (sample), never claiming this is live data.
Edge cases
Real endpoint rejects the page
A weather service may require a key or disallow the page origin.
Use the provider documentation and an appropriate server-side integration. Do not paste secret keys into the browser or try no-cors as a readable-data fix.
Wrong response shape
A provider may nest temperature under a different field.
Map and validate its response before display. This sample checks its own documented city, tempC, and condition fields.
What's going on
This weather app displays a city, temperature, and condition from sample data. It teaches the shape of a weather screen without pretending that an invented web address supplies real forecasts. The default example works without an account, an API key, or a network request.
getWeather returns a promise, which provides a value after an operation finishes. The button waits for that value, checks the expected fields, and writes a clear sentence to the page. tempC states the unit explicitly, so 27 is not mistaken for a Fahrenheit reading.
The unused network branch shows where fetch would go. Its .invalid address is a deliberate placeholder, not a service to call. Before using a real provider, replace the address, map its actual JSON fields, and follow its access rules. CORS is a browser rule that requires the other server to allow your page to read its response. A browser cannot fix missing CORS permission. Secret API keys belong on a server you control, not in public page code.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Does the default click call a weather server?
Pick an answer to check it.
Question 2
Where should a secret provider key live?
Pick an answer to check it.
Questions people ask
Is 27 °C the current Pune temperature?
No. It is fixed teaching data and is labelled sample on the page.
Why use an .invalid address?
It clearly marks a non-working placeholder. You must choose a real permitted service before enabling the network branch.
Why check response.ok?
fetch can resolve for HTTP errors such as 404. response.ok separates successful HTTP responses from those errors.