Checking to see if a given number exists in an array

if i run this code, it keeps showing me undefined . Please what should i do.

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

function include(array, searchElement) {
array.forEach(i => {
return i === searchElement;
});
}

console.log(include(numbers, 2));

forEach is a consumer. It does not produce(return)

function include(array, searchElement) {
array.forEach((element) => {
if (element === searchElement) {
console.log(${element} is in array);
} else {
console.log(${element} is not in array);
}
});
}

console.log(include(numbers, 2));

If the purpose of the function is to return a boolean indicating that the element was included in the array, then @Potato86’s answer will not quite work.

Personally, I would write the function using the find() method:

function include(array, searchElement) {
  return array.find(element => element === searchElement) !== undefined;
}

If you must loop through the elements manually, you could write it like this:

function include(array, searchElement) {
  for (const element of array) {
    if (element === searchElement) {
      return true;
    }
  }
  return false;
}

Both of these would allow you to call console.log(include(numbers, 2)); and have it print out true.

1 Like