EN
JavaScript - check if array contains value
3
points
In this article, we would like to show you how to check if array contains value using JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
const array = ['a', 'b', 'c'];
console.log(array.indexOf('b') !== -1); // true
Hint: this solution works even in older web browsers and Node.js.
or:
// ONLINE-RUNNER:browser;
const array = ['a', 'b', 'c'];
console.log(array.includes('b')); // true
Warning:
Arrayincludes()was introduced in ES6 (around 2016).
Practical examples
1. Array indexOf() method
In this example, we use includes() method to check if letters array contains specific characters.
// ONLINE-RUNNER:browser;
const letters = ['a', 'b', 'c'];
console.log(letters.indexOf('b') !== -1); // true
console.log(letters.indexOf('x') !== -1); // false
with numbers:
// ONLINE-RUNNER:browser;
const numbers = [1, 2, 3];
console.log(numbers.indexOf(1) !== -1); // true
console.log(numbers.indexOf(4) !== -1); // false
2. Array includes() method
In this example, we use includes() method to check if letters array contains specific characters.
// ONLINE-RUNNER:browser;
const letters = ['a', 'b', 'c'];
console.log(letters.includes('b')); // true
console.log(letters.includes('x')); // false
with numbers:
// ONLINE-RUNNER:browser;
const numbers = [1, 2, 3];
console.log(numbers.includes(1)); // true
console.log(numbers.includes(4)); // false
Reusable function
In this section, you can find a function that works in older and modern web browsers or Node.js.
// ONLINE-RUNNER:browser;
const containsItem = (array, item) => array.indexOf(item) !== -1;
// Usage example:
const letters = ['a', 'b', 'c'];
console.log(containsItem(letters, 'b')); // true
console.log(containsItem(letters, 'x')); // false