How to check if an array includes a value in JavaScript


In JavaScript, you can check if an array includes a value in several ways. Here are some examples:

Using the includes() method:

const array = [1, 2, 3, 4, 5];
console.log(array.includes(3)); // Output: true
console.log(array.includes(6)); // Output: false

Using the indexOf() method:

const array = [1, 2, 3, 4, 5];
console.log(array.indexOf(3) !== -1); // Output: true
console.log(array.indexOf(6) !== -1); // Output: false

Using a for loop:

const array = [1, 2, 3, 4, 5];
let found = false;
for (let i = 0; i < array.length; i++) {
  if (array[i] === 3) {
    found = true;
    break;
  }
}
console.log(found); // Output: true

Note that the includes() and indexOf() methods work for arrays of primitive types (like numbers and strings), but may not work as expected for arrays of objects, since they compare object references rather than object values. In that case, you may need to use a loop or another method to compare the object values.