Why is the second condition satisfied if the first is already true?

  • 0
    After entering the correct letter, I get alert ('You guessed the letter:' + guess); and immediately after this message it issues alert ('You did not guess the letter'), although this is already the second condition and it is false, why is that?
    let words = [
        'луч'
    ];
    
    let word = words[Math.floor(Math.random() * words.length)];
    
    let answerArr = [];
    for (i = 0; i < word.length; i++ ) {
            answerArr[i] = '_';    
        }
    
    let remainingLetters = word.length;
    let attempt = 0;
    
    while (remainingLetters > 0 && attempt <= 3) {
        alert(answerArr.join(' '));
        let guess = prompt('Введите букву:');
        if (guess === null) {
        break;
        } else if (guess.length !== 1) {
            alert('Вводить можно только одну букву!');
        } else { 
            for (let h = 0; h < word.length; h++) {
                if (word[h] === guess) {
                    answerArr[h] = guess;
                    alert('Вы угадали букву: ' + guess);
                    remainingLetters--;
                } else if (word[h] !== guess) {
                    alert('Вы не угадали букву');
                    attempt++;
                    break;
                }    
            };
        };
    };
    JavaScript Blake Carey, Nov 20, 2019

  • 1 Answers
  • 0
    Because your program logic is incorrect in principle.

    Let's say you entered the letter 'y'. Your code will do the checks:

    'л' === 'у'?  нет.
    'л' !== 'у'? да. Вывод сообщения 'Вы не угадали букву'.
    'у' === 'у'? да. Вывод сообщения 'Вы угадали букву: у'.
    'ч' === 'у'? нет.
    'ч' !== 'у'? да. Вывод сообщения 'Вы не угадали букву'.


    The message should be displayed based on the results of checking all letters of the word, not for each letter.

    Letters already guessed should be excluded from the check.
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!