Example:
<!DOCTYPE html> <html lang="en"> <head> <title>JavaScript Random Word Generator</title> </head> <body> <h1>JavaScript Random Word Generator</h1> <p>Click the button to generate 3 random words.</p> <input type='button' value='Generate Words' onclick='getRandomWords(3)' /> <p id='result'></p> </body> <script> let getRandomWords = (number_of_words) => { const words = ['abacus', 'abandon', 'brain', 'brake', 'branch', 'crazy', 'cream', 'create', 'doctor', 'document', 'documentary']; let randomWords = []; for (let i = 0; i < number_of_words; i++) { let randomIndex = Math.floor(Math.random() * words.length); // console.log(randomIndex); randomWords.push(words[randomIndex]); } let generatedWords = randomWords; document.getElementById('result').innerHTML = generatedWords.join('<br/>'); } </script> </html>
I have defined a funtion named "getRandomWords()" that takes a parameter (a number). The function is called (with a default value of 3 for the parameter or argument) when someone clicks the button.
A list of predefined words are stored in an array.
Next, it loops through each word in the array, picks up 3 random words and stores it in another array.
randomWords.push(words[randomIndex]);
🚀 Generate Random English Words with definition
What's interesting is how it picks up a random word from the list of predefined array.
See the below code.
let randomIndex = Math.floor(Math.random() * words.length);
Array elements in JavaScript are accessed using the index number. The index starts with zero, followed by one and so on.The above formula Math.floor(Math.random() * words.length); generates a random number between 0 and the number of array elements. It is rounded up using the Math.floor() function. What we get is a random index that is matched with the index value in the array (of words). And so it returns a random word.