๐ค๏ธ Weather App - Fetch and display weather data from API. Advanced beginner to intermediate!
๐ Concepts Covered:
โข Fetch API / Async/Await
โข JSON parsing
โข Error handling
โข Template literals
โข Object destructuring
โจ Features:
โข Get weather by city
โข Display temperature
โข Show conditions
โข Error handling
โข Format output
javascript
// Weather App (Simulated API)
class WeatherApp {
constructor() {
// Simulated weather database
this.weatherData = {
"Yangon": { temp: 32, condition: "Sunny", humidity: 70, wind: 15 },
"Mandalay": { temp: 35, condition: "Hot", humidity: 50, wind: 10 },
"Naypyidaw": { temp: 30, condition: "Cloudy", humidity: 65, wind: 12 }
};
}
async getWeather(city) {
// Simulate API delay
await new Promise(resolve => setTimeout(resolve, 100));
const data = this.weatherData[city];
if (!data) {
throw new Error(`Weather data for "${city}" not found`);
}
return {
city: city,
temperature: data.temp,
tempFahrenheit: this.celsiusToFahrenheit(data.temp),
condition: data.condition,
humidity: data.humidity,
wind: data.wind
};
}
celsiusToFahrenheit(celsius) {
return Math.round((celsius * 9/5) + 32);
}
formatWeather(weather) {
return `
๐ค๏ธ Weather in ${weather.city}
โโโโโโโโโโโโโโโโโโโโโโโโโโ
๐ก๏ธ Temperature: ${weather.temperature}ยฐC (${weather.tempFahrenheit}ยฐF)
โ๏ธ Condition: ${weather.condition}
๐ง Humidity: ${weather.humidity}%
๐จ Wind: ${weather.wind} km/h
`;
}
}
// Demo usage with async/await
const app = new WeatherApp();
async function displayWeather() {
try {
const weather1 = await app.getWeather("Yangon");
console.log(app.formatWeather(weather1));
const weather2 = await app.getWeather("Mandalay");
console.log(app.formatWeather(weather2));
// This will throw an error
await app.getWeather("Tokyo");
} catch (error) {
console.log(`โ Error: ${error.message}`);
}
}
displayWeather();You should see
๐ค๏ธ Weather in Yangon โโโโโโโโโโโโโโโโโโโโโโโโโโ ๐ก๏ธ Temperature: 32ยฐC (90ยฐF) โ๏ธ Condition: Sunny ๐ง Humidity: 70% ๐จ Wind: 15 km/h ๐ค๏ธ Weather in Mandalay โโโโโโโโโโโโโโโโโโโโโโโโโโ ๐ก๏ธ Temperature: 35ยฐC (95ยฐF) โ๏ธ Condition: Hot ๐ง Humidity: 50% ๐จ Wind: 10 km/h โ Error: Weather data for "Tokyo" not found