skip to Main Content

Q: The Question Is code a function which will be able to take a word and locate the position of a chosen letter in that given word.

function letterFinder(word,match){
   for(let i=0; i==word.length; i++){
      if(word[i]==match){
        console.log('Found the', match, 'at', i);
      }
      else{
        console.log('---No match found at',i);
      }
   }
}
word="test";
letter="t";
letterFinder(word,letter)

My Output look like this:

 Found the t at 0
 ---No match found at 1
 ---No match found at 2
 Found the t at 3

2

Answers


  1. The issue in the given code lies within the for loop condition. The loop will never execute because the condition i == word.length is not met initially. The loop should run as long as i is less than word.length, not when it is equal to it.

    To correct the code, you should change the for loop condition from i == word.length to i < word.length

    Login or Signup to reply.
  2. Your for loop is wrong. Correct it as :

    for(let i=0; i < word.length; i++) { }
    
    function letterFinder(word,match){
       for(let i=0; i < word.length; i++){
          if(word[i]==match){
            console.log('Found the', match, 'at', i);
          }
          else{
            console.log('---No match found at',i);
          }
       }
    }
    word="test";
    letter="t";
    console.log(letterFinder(word,letter))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search