[SOLVED] Why does function return false after checking only one value in loop

Issue

Trying to check if a value exists within an array, but my nested if statement is returning
false even if the value exists in the array. This worked until I added an else to my loop, now it only works if the value to check for is the first index.

var num = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var inp = parseInt(prompt("Enter a number to see if it is in the array:"));

function checkIfInArray(n, anArray) {

  for (var i = 0; i < anArray.length; i++) {
    if (num[i] == n) {
      return true;
    } else {
      return false;
    }
  }
}

console.log(checkIfInArray(inp, num));

Solution

Even though you have the check inside the for-loop, the code inside the for-loop runs only once because now that you’ve added an else, it will ALWAYS return something.

The correct way to return false if nothing was found, would be to add the return false after the for-loop finishes.

for(var i = 0;i < anArray.length;i++)
{
     if(num[i] == n)
     {
          return true;
     }
} 

return false;

Answered By – Cloud SME

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.