0

I'm trying to create a simple search function in JavaScript by asking for an array and an item and then looping through the array items if there's a match, return true, else, return false.

function encontrar(array, item){
  var n = array.length;
  
  for (var i = 0; i <= n; i++){
    if(array[i] == item){
      return true; 
    }
    else{
      return false;
    } 
  }
}
console.log(encontrar(numeros, 3))

The function will only return true for items index 0

2
  • For completeness I must add that you could have used array.indexOf(item)>-1 Commented Jul 9, 2022 at 23:24
  • function encontrar(array, item){ return array.includes(item); } Commented Jul 9, 2022 at 23:45

2 Answers 2

2

It makes more sense if you return false only after the loop of searching. In addtion, note the length of the loop.

var numeros = [1,2,4,3];

function encontrar(array, item) {
  var n = array.length;

  for (var i = 0; i < n; i++) {
    if (array[i] == item) {
      return true;
    }
  }
  return false;
}
console.log(encontrar(numeros, 3))

Sign up to request clarification or add additional context in comments.

Comments

2

This should work:

function encontrar(array, item){
  var n = array.length;
  
  for (var i = 0; i < n; i++){
    if(array[i] == item){
      return true; 
    }
  }
  
  return false;
}

When the return false; is hit, it immediately returns. This means it has to be outside the loop body, or you will only check the first item before returning false.

Also note that it should be i < n, not i <= n.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.