Select Random Item from an Array

var myArray = [

var randomItem = myArray[Math.floor(Math.random()*myArray.length)];

See the Pen gLJPZv by Chris Coyier (@chriscoyier) on CodePen.


  1. User Avatar
    Adam Lemmo
    Permalink to comment#

    This is super succicnt, and here I was doing this all the time like a total schmo…

    JS Result
    function randomNum(minVal, maxVal) {
    do {
    r = Math.random();
    } while (r == 1);
    return minVal+Math.floor(r*(maxVal+1-minVal));
    var coolwords = new Array();
    coolwords[0] = “robot”;
    coolwords[1] = “inferno”;
    coolwords[2] = “giga”;
    coolwords[3] = “infinity”;
    coolwords[4] = “pow”;
    coolwords[5] = “smash”;
    coolwords[6] = “boom”;
    coolwords[7] = “crunch”;
    coolwords[8] = “robot”;
    coolwords[9] = “inferno”;

    document.body.innerHTML = coolwords[randomNum(0, coolwords.length-1)];

  2. User Avatar
    Permalink to comment#

    var mrrandom = Math.floor(Math.random()*10);

    This is Best example. you can try it.

Leave a Comment

Posting Code!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.