JavaScript - 26

JavaScript - 26: Random Quote Generator

Create a button that displays a random quote from an array.

Your challenge: Store several quotes in an array, choose one at random, and display it when the button is clicked.

✦ JavaScript Editor
▶ Live Output

Choose a random array item

Math.random() creates a random decimal number between 0 and almost 1.

Use: Math.floor(Math.random() * quotes.length)

This creates a random valid index for the quotes array.

Display the quote

Use the random index to get one quote: quotes[randomIndex]

Then place it on the page with quoteText.textContent.

Run it on a click

Add getRandomQuote as the button's click event listener.

Call the function once more when the page loads so a quote appears immediately.

Try it: Click New Quote several times and watch different array items appear.

Good JavaScript habit: Use array.length instead of typing the number of items yourself. The code will still work if you add or remove quotes later.

👀 Show Solution
const quotes = [
  "Small steps still move you forward.",
  "Curiosity turns questions into skills.",
  "Practice makes difficult things feel familiar.",
  "A clear plan makes a big task feel smaller.",
  "Mistakes are useful when you learn from them."
];

const quoteText = document.getElementById("quote");
const newQuoteBtn = document.getElementById("newQuoteBtn");

function getRandomQuote() {
  const randomIndex = Math.floor(Math.random() * quotes.length);
  quoteText.textContent = quotes[randomIndex];
}

newQuoteBtn.addEventListener("click", getRandomQuote);

getRandomQuote();

The random number becomes an array index, and that quote is displayed with textContent.