Console log not printing variable from function

29,925

The variable randomWord is out of the scope. You define the variable inside a function, and then call it outside of it.

You should either define the variable out of the function or call it inside of it:

function strt(){
   var randomWord;
   ...
   console.log(randomWord);
   return randomWord;
}//end strt()

Or

var randomWord;
function strt(){
   ...
   return randomWord;
}//end strt()
strt(); // Call the function
console.log(randomWord);

For the latter, consider that randomWord won't have changed when JS executes the console log function; therefore, it will be null. In other words, you must call the function before you log it.

Share:
29,925
oxxi
Author by

oxxi

Just a coder trying to get better so I can get a good job and buy a house one day.

Updated on March 29, 2020

Comments

  • oxxi
    oxxi about 4 years

    Trying to print the variable 'randomWord' to console.log, but chrome says it is not defined. It looks like it's defined to me. Why won't it print to the console.log?

    function strt(){
    
    //get random word from words[] array
    var randomWord = words[Math.floor(Math.random()* words.length)];
    
    var wordLength = randomWord.length;
    
    
    //create a blank boxes or div elements for holding each letter of 
    // selected random word
    for(i = 0 ; i< wordLength; i++){
    
    var divTag = document.createElement("div");
    divTag.id = "div" + i;
    divTag.className = 'wordy';
    //divTag.innerHTML = randomWord[i];
    hangManDiv.appendChild(divTag);
    
    };// end for loop
    
    //disable start button
    document.getElementsByName("startB")[0].disabled = true;
    
    return randomWord;
    
    }//end strt()
    
    console.log(randomWord);