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

3
  • 1
    JavaScript array already has an includes Commented Dec 9, 2019 at 12:07
  • Also, you get false because return immediately ends the function. Thus you only get the first result of the loop. Commented Dec 9, 2019 at 12:08
  • you can use indexOf to check whether value exist in the array or not Commented Dec 9, 2019 at 12:12

1 Answer 1

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

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

1 Comment

You should still return false to be consistent with the boolean results. But that has to happen after the loop.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.