TIL: Random choice from Javascript array

Published September 11, 2025

I set up a custom 404 page and wanted to randomize the message it gives. So I looked into how to make a random choice from an array in Javascript. I know how to do this in Python - it's pretty easy there:


from random import choice
choice(list(range(1, 11)))

will give you a random number between 1 and 10 (please don't at me that it's not truly random.) But a Javascript expert I am not. I am, at best, a dabbler. So I went to the interwebs and looked. This is what I came up with


      function getTextSelection() {
          const randomItem = ["option1", "option2", "option3"];
          let randomIndex = Math.floor(Math.random() * randomItem.length);
          return randomItem[randomIndex];
      }

and it works wonderfully for what I want to do. The trick here is that Math.random gives you a floating point 0 <= n < 1 so if you multiply it by the length of the array you get a randomized, valid, index in the array.


Previous: git exclude Next: How to configure the Python REPL