1

I am new in javascript and maybe the below code has some return error. what I trying to do is find a specific number in a JavaScript array.

const numberList = [1, 2, 3, 4];

function includes(arrays, searchElement) {
  for (let elements of arrays) {
    if (elements === searchElement) {
      return true;
    } else {
      return false;
    }
  }
}
console.log(includes(numberList, 3))
VLAZ
  • 26,331
  • 9
  • 49
  • 67
Kiran
  • 25
  • 5
  • 1
    JavaScript array [already has an includes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) – Liam Dec 09 '19 at 12:07
  • Also, you get `false` because `return` immediately ends the function. Thus you only get the *first* result of the loop. – VLAZ Dec 09 '19 at 12:08
  • you can use `indexOf` to check whether value exist in the array or not – Narendra Chouhan Dec 09 '19 at 12:12

1 Answers1

1

You should not return when if the condition is false. Instead you can return false from outside of the loop:

const numberList = [1, 2, 3, 4];

function includes(arrays, searchElement) {
  for (let elements of arrays) {
    if (elements === searchElement) {
      return true;
    }
  }
  return false;
}
console.log(includes(numberList, 3))

Though you can use the built-in includes() to achieve the same:

const numberList = [1, 2, 3, 4];
const IsExist = (numberList, search) => numberList.includes(search)? true : false;
console.log(IsExist(numberList, 3));
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • You should still return `false` to be consistent with the boolean results. But that has to happen *after* the loop. – VLAZ Dec 09 '19 at 12:10