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:
xxxxxxxxxx
1
const array = ['a', 'b', 'c'];
2
3
console.log(array.indexOf('b') !== -1); // true
Hint: this solution works even in older web browsers and Node.js.
or:
xxxxxxxxxx
1
const array = ['a', 'b', 'c'];
2
3
console.log(array.includes('b')); // true
Warning:
Array
includes()
was introduced in ES6 (around 2016).
In this example, we use includes()
method to check if letters
array contains specific characters.
xxxxxxxxxx
1
const letters = ['a', 'b', 'c'];
2
3
console.log(letters.indexOf('b') !== -1); // true
4
console.log(letters.indexOf('x') !== -1); // false
with numbers:
xxxxxxxxxx
1
const numbers = [1, 2, 3];
2
3
console.log(numbers.indexOf(1) !== -1); // true
4
console.log(numbers.indexOf(4) !== -1); // false
In this example, we use includes()
method to check if letters
array contains specific characters.
xxxxxxxxxx
1
const letters = ['a', 'b', 'c'];
2
3
console.log(letters.includes('b')); // true
4
console.log(letters.includes('x')); // false
with numbers:
xxxxxxxxxx
1
const numbers = [1, 2, 3];
2
3
console.log(numbers.includes(1)); // true
4
console.log(numbers.includes(4)); // false
In this section, you can find a function that works in older and modern web browsers or Node.js.
xxxxxxxxxx
1
const containsItem = (array, item) => array.indexOf(item) !== -1;
2
3
4
// Usage example:
5
6
const letters = ['a', 'b', 'c'];
7
8
console.log(containsItem(letters, 'b')); // true
9
console.log(containsItem(letters, 'x')); // false