Rachel Warbelow
Rachel Warbelow

Reputation: 23

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 = ""
        };
    });
});

Upvotes: 2

Views: 144

Answers (2)

MasqueradeCircus
MasqueradeCircus

Reputation: 854

The problem was the var word in your keypress event as Niranjan said. And, i don't know if this is better for you. If it is, try it. With this you eliminate the possibility of choose a duplicated word.

var words = ["elephant", "puppy", "cat", "table", "staircase"];
words.sort(function() { return 0.5 - Math.random() };
var currentWord = 0;
var chosenWord = words[0];
var typedWord = "";
$(document).ready(function(){
    $('.word-box').html(chosenWord);
    $(document).keypress(function(e) {
        typedWord += letters[e.which];
        if (typedWord === chosenWord && currentWord < words.length - 1) {
            currentWord++;
            chosenWord = words[currentWord];
            $('.word-box').html(chosenWord);
            typedWord = "";
        };
    });
});

Upvotes: 0

Niranjan Borawake
Niranjan Borawake

Reputation: 1638

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.

Upvotes: 4

Related Questions