'Generate and display random message – JavaScript

For the website that I am creating, I am looking to have a random welcome message be generated using a JavaScript array and be displayed on the screen using the innerHTML property. So far, I've created the array with the messages, but I'm stuck on how to select a random one, then insert it using the innerHTML property. Any help would be awesome.



Solution 1:[1]

Try this https://jsfiddle.net/ywnv00xc/1/

const messages = ['message1', 'message2', 'message3', 'message4'];
const randomIndex = Math.round(Math.random()*messages.length);
document.getElementById("your-elements-id").innerHTML = messages[randomIndex];

Solution 2:[2]

From MDN:

const getRandomArbitrary = (min, max) => {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 slothstronaut