HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Displaying random quotes from an array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
randomarrayquotesdisplayingfrom

Problem

Is there anything that I could have done better in this code?


Quotes

body { color: #333; font: 20px georgia; }
em { color: #555; font-size: 90%; }

(function() {
  "use strict";

  var quotes = [
    ["Stay Hungry. Stay Foolish.", "Steve Jobs"],
    ["Good Artists Copy, Great Artists Steal.", "Pablo Picasso"],
    ["Argue with idiots, and you become an idiot.", "Paul Graham"],
    ["Be yourself; everyone else is already taken.", "Oscar Wilde"],
    ["Simplicity is the ultimate sophistication.", "Leonardo Da Vinci"]
  ].sort(function() {
    return 0.5 - Math.random();
  }),
    quotesHTML = "";

  for (var i = 0; i “" + quotes[i][0] + "” — " + quotes[i][1] + "";
  }
  document.getElementById("quotes").innerHTML = quotesHTML;

}());

Solution

I think your code looks pretty good already. It follows conventions and your indentation and variable names are precise. There's not much to review.

But if you're targeting modern browsers (IE9+) I would suggest a different approach using map and would separate the random logic into a function. I'd also declare the element up top so I know at first glance that the code is working with the DOM. It may seem like more code at first but it's good for code reuse, plus I think it reads better; the intent is more clear:

(function() {
  "use strict";

  var el = document.getElementById("quotes");

  var quotes = [
    ["Stay Hungry. Stay Foolish.", "Steve Jobs"],
    ["Good Artists Copy, Great Artists Steal.", "Pablo Picasso"],
    ["Argue with idiots, and you become an idiot.", "Paul Graham"],
    ["Be yourself; everyone else is already taken.", "Oscar Wilde"],
    ["Simplicity is the ultimate sophistication.", "Leonardo Da Vinci"]
  ];

  function rand(xs) {
    return xs.slice(0).sort(function(){
      return .5 - Math.random();
    });
  }

  function quote(q) {
    return "“"+ q[0] +"” — "+ q[1] +"";
  }

  el.innerHTML = rand(quotes).map(quote).join('');

}());

Code Snippets

(function() {
  "use strict";

  var el = document.getElementById("quotes");

  var quotes = [
    ["Stay Hungry. Stay Foolish.", "Steve Jobs"],
    ["Good Artists Copy, Great Artists Steal.", "Pablo Picasso"],
    ["Argue with idiots, and you become an idiot.", "Paul Graham"],
    ["Be yourself; everyone else is already taken.", "Oscar Wilde"],
    ["Simplicity is the ultimate sophistication.", "Leonardo Da Vinci"]
  ];

  function rand(xs) {
    return xs.slice(0).sort(function(){
      return .5 - Math.random();
    });
  }

  function quote(q) {
    return "<p>&ldquo;"+ q[0] +"&rdquo; &mdash; <em>"+ q[1] +"</em></p>";
  }

  el.innerHTML = rand(quotes).map(quote).join('');

}());

Context

StackExchange Code Review Q#41269, answer score: 8

Revisions (0)

No revisions yet.