Beginner 10 minutes
Build a Joke Machine
Create a joke generator that fetches random jokes by category. No API key required - just instant laughs.
What You'll Build
A joke machine that fetches random jokes by category and handles both single-line and two-part joke formats.
Prerequisites
- ✓ Basic JavaScript knowledge
1
Fetch a random joke
JokeAPI requires no authentication. It returns jokes in two formats: single-line jokes and setup/delivery jokes.
javascript
const response = await fetch('https://v2.jokeapi.dev/joke/Any?safe-mode');
const joke = await response.json();
if (joke.type === 'single') {
console.log(joke.joke);
} else {
console.log(joke.setup);
console.log(`... ${joke.delivery}`);
} 2
Filter by category
Choose from categories like Programming, Pun, Dark, Misc, Spooky, and Christmas.
javascript
// Get a programming joke
const progRes = await fetch('https://v2.jokeapi.dev/joke/Programming?safe-mode');
const progJoke = await progRes.json();
console.log('Programming joke:');
console.log(progJoke.type === 'single' ? progJoke.joke : `${progJoke.setup} - ${progJoke.delivery}`);
// Get a pun
const punRes = await fetch('https://v2.jokeapi.dev/joke/Pun?safe-mode');
const pun = await punRes.json();
console.log('\nPun:');
console.log(pun.type === 'single' ? pun.joke : `${pun.setup} - ${pun.delivery}`); 3
Build a joke function with options
Create a reusable function that supports multiple categories and language options.
javascript
async function getJoke(category = 'Any', lang = 'en') {
const url = `https://v2.jokeapi.dev/joke/${category}?safe-mode&lang=${lang}`;
const response = await fetch(url);
const joke = await response.json();
if (joke.error) {
return 'No joke found for that category.';
}
return joke.type === 'single'
? joke.joke
: `${joke.setup}\n${joke.delivery}`;
}
// Get jokes from different categories
const jokes = await Promise.all([
getJoke('Programming'),
getJoke('Pun'),
getJoke('Misc')
]);
jokes.forEach((joke, i) => {
console.log(`\nJoke ${i + 1}:`);
console.log(joke);
}); Next Steps
- → Build a web page with category buttons
- → Add a 'share joke' button that copies to clipboard
- → Set up a Slack bot that posts daily jokes