JavaScript For Loop with Math.random Beginners

Hi everyone,

This is the script created by me for learning purposes.
I’ve succeed in displaying each cat from the table with the “for loop” and I decided to create something more advanced :slight_smile: So, I’ve added a Math Random method. But, I don’t understand why it’s displaying the letters from the table instead of displaying full cat’s names. Could you please help me to fix this script, so it displays full cat’s names randomly. Thank you very much in advance.

        <p id="cats-list"></p>

<script>

    var cats =  ["Pluffy", "Kitty", "Lily"];
    var text = "";
    var i;

    var catRandom = cats[Math.floor(Math.random()*cats.length)];

    for (i = 0; i < cats.length; i ++) {
        text += catRandom[i] + " is my favourite cat" + "<br>";
    }

    document.getElementById("cats-list").innerHTML = text;
</script>

catRandom is not an array but a just a single value (from your cats array) and in the for loop it is being treated as an array of characters, giving you the letters from that particular name.
The easiest way to fix it is to add the variable j, and in the for loop just before text add
j = Math.floor(Math.random()*cats.length);
and then change catRandom[i] to cats[j];

1 Like