Check for a value in a JavaScript Array
Three JavaScript functions that you can use to check if a value exists in an array.
1 min read
Here are three JavaScript functions that can help you check for a value in an array. Keep in mind that they are all case-sensitive.
Using includes()
const fruits = ['apple', 'banana', 'peach'];
fruits.includes('apple'); // true
fruits.includes('mango'); // false
Using indexOf()
indexOf()
will return -1
when the item is not found.
const fruits = ['apple', 'banana', 'peach'];
fruits.indexOf('apple'); // 0
fruits.indexOf('apple') !== -1; // true
fruits.indexOf('rasberry'); // -1
Using some()
const foods = ['pasta', 'pizza', 'chicken'];
foods.some(food => food === 'pasta'); // true
foods.some(food => food === 'fish'); // false
some()
can also be used with an array of objects.
const foods = [{ name: 'beef' }, { name: 'chicken' }];
foods.some(item => item.name === 'beef'); // true
foods.some(item => item.name === 'fish'); // false