Home > Back-end >  .includes() Is always returning true
.includes() Is always returning true

Time:12-13

I am trying to make a Wordle type game, I have started on the basics where it is just using the console to tell me weather the letters are correct or not. In the function check letter the first if statement works flawlessly but on the second one when it is checking weather or not the guess and the word both have the same letter just not in the correct spot. But even when the letter is not even in both of the variable it will console "wrong spot" instead of "wrong letter".

const word = "Lucas";
let guessed = prompt("Please Guess The Word");
checkLength()

function checkLength() {
  if (word.length == guessed.length) {
    console.log("It Worked")
    checkLetter(0)
    checkLetter(1)
    checkLetter(2)
    checkLetter(3)
    checkLetter(4)
  } else {
    console.log("It Failed")
    guessed = prompt("Please Use 5 Letters");
  }
}

function checkLetter(letterPos) {
  if (word.charAt(letterPos) == guessed.charAt(letterPos)) {
    console.log("Same Letter! "   letterPos)
  } else {
    let letterW = word.charAt(letterPos)
    let letterG = guessed.charAt(letterPos)
    if (word.includes(letterW) == guessed.includes(letterG)) {
      console.log("Wrong Spot "   letterPos)
    } else {
      console.log("Wrong Letter "   letterPos)
    }
  }
}

CodePudding user response:

The problem is that includes returns true or false, not the index, so when both world and guessed don't include the letter, false == false would return true:

if (letterG !== letterw && word.includes(letterW))

The above condition should work.

CodePudding user response:

First, we should clean up the variables. Then, all that needs fixing is the second if statement. We want to check if letterG exists in word, if not, then it's the wrong letter.

function checkLetter(letterPos) {
    let letterW = word.charAt(letterPos);
    let letterG = guessed.charAt(letterPos);

    if (letterW == letterG) {
        console.log("Same Letter! "   letterPos)
    } else {
        if (word.includes(letterG)) {
            console.log("Wrong Spot "   letterPos)
        } else {
            console.log("Wrong Letter "   letterPos)
        }
    }
}

  • Related