codingn00b
codingn00b

Reputation: 15

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

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));

Upvotes: 0

Views: 918

Answers (5)

tenshi
tenshi

Reputation: 618

I came across a similar problem while doing my react app. We can use Array.some(), this will return true if atleast one condition is true.

const array = [1, 2, 3, 4, 5];

const twoExists = array.some(value => value === 2)
console.log(twoExists)
// expected output: true

Upvotes: 0

Veve
Veve

Reputation: 6758

Your function will stop & exit at the first "return". If you add a return false after the loop, it will ensure that if the function haven't been exited after the loop (= not in array), it will return false :

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;
        }
    }
    
    return false;
}

var result = checkIfInArray(inp,num);
console.log(result)

Upvotes: 0

Chinedu
Chinedu

Reputation: 171

You have an if statement to return at first check, whether true or false

Upvotes: 0

belykh
belykh

Reputation: 1290

You should use this:

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

Upvotes: 0

Andy T
Andy T

Reputation: 9881

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;

Upvotes: 3

Related Questions