Can Someone Please Explain How The Js Code Works.

Discussion in 'JavaScript' started by Kamal42, Jan 21, 2013.

  1. #1
    var wordLetters    = ['G', 'O', 'A', 'T'];
    var guessedLetters  = ['_', '_', '_', '_'];
     
    function guessLetter(letter) {
        var goodGuess = false;
        var moreToGuess = false;
        for (var i = 0; i < wordLetters.length; i++) {
            if (wordLetters[i] == letter) {
                guessedLetters[i] = letter;
                goodGuess = true;
            }
            if (guessedLetters[i] == '_') {
                moreToGuess = true;
            }
        }
        if (goodGuess) {
            alert('Yay, you found a letter!');
            document.write(guessedLetters.join(''));
            if (!moreToGuess) {
                alert('YOU WON!');
            }
        } else {
            alert('Oh noes, thats not right!');
        }
    }
     
    guessLetter('G');
    guessLetter('I');
    guessLetter('O');
    guessLetter('A');
    guessLetter('T');
    Code (markup):

     
    Last edited: Jan 21, 2013
    Kamal42, Jan 21, 2013 IP
  2. phpexperts

    phpexperts Greenhorn

    Messages:
    12
    Likes Received:
    0
    Best Answers:
    1
    Trophy Points:
    21
    #2
    There is a two array that is wordLetters, guessedLetters.

    guessLetter is a function.

    guessLetter('G'); will call function guessLetter.

    Now the for loop will check the latter is available in array "wordLetters" or not
    if it will available in array then set goodGuess = true; and set that latter in guessedLetters it will check for whole array "wordLetters".

    After that on line 16 it will check for goodGuess if it's true than alert will be display and print guessletters array with space i.e. (' ') on next statement check condition for more to guess if not then display alert "YOU WON!"

    same process will done for all other functions.

    Hope this is this is enough to explain this js code :)
     
    phpexperts, Jan 22, 2013 IP