Check for a value in a JavaScript Array

Three JavaScript functions that you can use to check if a value exists in an array.
July 02, 2020JavaScript
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('raspberry'); // -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 => === 'beef'); // true

foods.some(item => === 'fish'); // false

Be React Ready

Learn modern React with TypeScript.

Learn modern React development with TypeScript from my books React Ready and React Router Ready.