0

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

1
  • Did you expect the function to return false; multiple times? How would that work? Commented Nov 25, 2014 at 16:59

5 Answers 5

3

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;
Sign up to request clarification or add additional context in comments.

Comments

0

You should use this:

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

Comments

0

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

Comments

0

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.