Why isn’t the else in my if-statement not returning the correct outputs?

56 Views Asked by At

I am working on coding in my Computer Science class and my function isn’t working correctly. I rewrote my code to make an example:

function getWords(userWord) {
  var returnList = [];
  var wordList = [blue, red,     purple];  

  for (var i = 0; i < wordList.length; i++) {
    if (userWorld == wordList[i]) {
      appendItem(returnList, wordList[i]);
      return returnList[];
    } else {
      return “Not Found.”;
    }
  }
}

I try this and it will only return “Not Found.” even if the word matches.

1

There are 1 best solutions below

0
On

If you are using JavaScript, I solved your issue. :)

You had some misspelling, and some errors in your code.

See, the problem is that return keyword stops the execution of your for loop once a condition is met. In your case, both if and else have return keyword in them, so your for loop will never execute more then once.

In other words, your if statement will work only if you put word 'blue'.

If you were to put word 'red', which is the second element in your array, you would obviously go into else statement, because variable i would be 0 (AKA 'blue' in your array). By going in else it will return 'Not found.' and it would stop the for loop completely.

Hope you understand now :)

Anyways, here is your solution friend, let me know if it works, or if you have any questions :

let word = 'purple';

function getWords(userWord) {

var returnList = [];

var wordList = ['blue', 'red', 'purple'];  

let boolCheck = false;

for (var i = 0; i < wordList.length; i++) {

    if(userWord == wordList[i]){

        boolCheck = true;

        returnList.push(wordList[i]);

    }

}

if(boolCheck){

    return returnList;

}

else{

    return "Not found.";

}

  }


let wordGet = getWords(word);

console.log(wordGet);