Search code examples
javascriptarraysfunctionconsole

Generate a random word from an array and then print it to the console log in a function in javascript


I am creating hangman in javascript and I have (I think) successfully generated a random word from an array in a function, to check if it works I am trying to print the generated word in to the console but it doesn't seem to be working here's my code for the function

    var word = function() //Random word is genereated from an array for the user to guess
{
  GameWordArray = new Array(7);
  GameWordArray[0] = "monitor";
  GameWordArray[1] = "program";
  GameWordArray[2] = "application";
  GameWordArray[3] = "keyboard";
  GameWordArray[4] = "javascript";
  GameWordArray[5] = "gaming";
  GameWordArray[6] = "network";
  randno = Math.floor(Math.random() * GameWordArray.length);
  document.write(GameWordArray[randno]);
  console.log(word);
}

Thanks in advance :)


Solution

  • Here is an example on jsfiddle

    var words = ["monitor", "program", "application", "keyboard", "javascript", "gaming", "network"];
    
    var word = words[Math.floor(Math.random() * words.length)];
    
    console.log(word);
    
    document.getElementById("word").textContent = word;
    

    And to have it fit in directly with you present code:

    var getRandomWord = function () {
        return words[Math.floor(Math.random() * words.length)];
    };