Search code examples
javascriptjquerykeypress

Why does variable become undefined inside of $(document).keypress?


Why would the alert on line 8 return "undefined"? If I alert the same thing on line 5, it returns a random word from the words array.

var words = ["elephant", "puppy", "cat", "table", "staircase"]
var chosenWord = words[Math.floor(Math.random()*words.length)]
var typedWord = ""
$(document).ready(function(){
$('.word-box').html(chosenWord)
    $(document).keypress(function(e) {
        typedWord += letters[e.which]
        alert(chosenWord)
        if (typedWord === chosenWord) {
            var chosenWord = words[Math.floor(Math.random()*words.length)]
            $('.word-box').html(chosenWord)
            typedWord = ""
        };
    });
});

Solution

  • Guess. The problem is this below line, inside the keypress event handler:

    var chosenWord = words[Math.floor(Math.random()*words.length)]
    

    When you declare a variable with var due to variable hoisting it is ad good as declaring it at the start of the function. So our code actually turns out to be :

    var words = ["elephant", "puppy", "cat", "table", "staircase"]
    var chosenWord = words[Math.floor(Math.random()*words.length)]
    var typedWord = ""
    $(document).ready(function(){
    $('.word-box').html(chosenWord)
        $(document).keypress(function(e) {
            //UPDATE
            var chosenWord;
            typedWord += letters[e.which]
            alert(chosenWord)
            if (typedWord === chosenWord) {
                //UPDATE
                chosenWord = words[Math.floor(Math.random()*words.length)]
                $('.word-box').html(chosenWord)
                typedWord = ""
            };
        });
    });
    

    Solution:

    Try removing the var before chosenWord inside the keypress event handler.

    Do have a look at var hoisting.