Check for a value in a JavaScript Array

Published July 2, 2020

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()

includes.js
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.

index-of.js
const fruits = ['apple', 'banana', 'peach'];

fruits.indexOf('apple'); // 0

fruits.indexOf('apple') !== -1; // true

fruits.indexOf('rasberry'); // -1

Using some()

some.js
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.

some-objects.js
const foods = [{ name: 'beef' }, { name: 'chicken' }];

foods.some(item => item.name === 'beef'); // true

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