MLK quote generator

Hey campers, I made a MLK random quote generator using javascript and css grid. check it out and let me know what you think. any feedback is appreciated. thank you

A small suggestion? Rather than hardcoding your random function, make it a bit more generic:

function random(max) {
  return Math.floor(Math.random() * max);
}

This will make the random() something you can use elsewhere, it’s a great addition to your personal code toolbox. Then, in your click handler, rather than getting:

quotes.featured[random()].quote + '"';

You can tell it what the random range is.

quotes.featured[random(quotes.featured.length)].quote + '"';

Doing that, if you ever decide to add more quotes, you won’t have to update the random function to match. It all happens without you needing to even think about it.

Your current approach, from a coding standpoint, is more brittle. It requires a number of moving parts, all independent of each other. By changing the random() to be more ‘generic’, and passing it what it needs to know to give you a number in a specified range, then having the click handler (which already KNOWS about quotes) tell random to use quotes.featured.length, the parts are interdepended in a sane, predictable manner.

@snowmonkey thank you for taking the time to look over my code and respond. Your response is exactly the type of feedback that helps me to become a better programmer. Thank you. Now, how would I go about making sure a quote is not displayed twice in a row? I am thinking some sort of if else statement. Is the current index of random() stored somewhere?

There are a couple of ways:

  1. you could randomly shuffle them when the page loads, then simply retrieve them from the array in order (which, at that point, WOULD be random).
  2. you could fetch the random quote, and Array.splice(...) it out of the array and push it onto a usedQuotes array. Then, when the original quotes array is empty, simply replace it with the usedQuotes and recycle them, over and over.

They’re basically the same thing – the first does the shuffle in advance, while the second is doing it as you go.