A joke generator is the friendliest API project there is: one button, one API call, one laugh. It is also a genuinely good way to learn async JavaScript, because the whole app is a single fetch() wrapped in a button click.
What you are building
An app with one button that fetches a random programming joke and shows it, with a loading state while the joke is on its way.
The JavaScript: the whole app
const jokeEl = document.querySelector('#joke');
const btn = document.querySelector('#new-joke-btn');
async function getJoke() {
btn.disabled = true;
jokeEl.textContent = 'Thinking of a joke...';
try {
const res = await fetch('https://official-joke-api.appspot.com/jokes/programming/random');
const data = await res.json();
const joke = data[0];
jokeEl.textContent = joke.setup + ' — ' + joke.punchline;
} catch (err) {
jokeEl.textContent = 'Could not fetch a joke. Check your connection and try again.';
}
btn.disabled = false;
}
btn.addEventListener('click', getJoke);
getJoke(); // Load one joke when the page opens
Two small details that matter
First, disabling the button while the request is in flight stops users from firing five requests at once. Second, loading one joke when the page opens means the app never shows an empty screen — the first thing a visitor sees is the app working.
Why this is a good learning project
The API needs no key and no signup, the response has only two fields you care about (setup and punchline), and the app has exactly one state to manage. When you move on to a weather app or a news feed, the code will look almost identical — only the URL and the field names change.
The one thing to remember
The API returns an array with one joke in it, not a single object. data[0] is the part beginners forget, and forgetting it produces the classic error of trying to read .setup from an array.
Top comments (0)