Answer the question
In order to leave comments, you need to log in
Why do both conditions work in the loop?
Hello, I'm learning js, I can't understand a little why if else works if the first if works. That is, if I enter the correct letter, the first condition should work and add this letter to the array, but the second condition says that "if the letter that is substituted by the cycle is not equal to the letter that was entered, display the messages ...", although the letter came up for my reasons already if else shouldn't work? Help me to understand.
The code itself
let res = [];
function nam(){
let guess = prompt();
let word = "cat";
let remain = word.length;
for(let i = 0; i < remain; i++){
if (guess == word[i]){
res[i] = guess;
remain--;
} else if(word[i] !== guess) alert("no")
}
}
Answer the question
In order to leave comments, you need to log in
Everything is correct. Look. Suppose you wrote the letter "c". We go through the cycle c == c ? Yes, we assign the value to the array, then the next value comes and here the values c == a are not equal, so the else if condition will be executed.
Probably the cycle can be rewritten on the ternary operator. Maybe someone has a better solution
let guess = prompt();
let word = "cat";
let remain = word.length;
word.includes(guess) ? res.push(guess) : alert('no')
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question