javascript

How to check a value contains in Javascript array


In this article, you will learn about how to check a value that contains in the JavaScript array.

An array in JavaScript can be stored different elements into a single variable. In JavaScript, elements can be a primitive value like String, Number, etc. JavaScript lets you check a value that exists in the array or not. To do so you have to use the includes() method.

Suppose you have a Numbers array that contains some random value. Now you want to know a particular number that contains in the array or not. See the below examples for the solution:

// value contains in array
const numbers = [10,20,30,40,50,60,70]
console.log(numbers.includes(40))

// Output : true

// value does not contains in array
const numbers = [10,20,30,40,50,60,70]
console.log(numbers.includes(400))

// Output : false

Note : includes() method returns a boolean value. If the value is found it returns true and if not it returns false.

JavaScript lets you do the same thing in String primitive type value. For example, if you have an array that contains names and you want to know a particular name that contains or not then you can use the includes() method to execute it.

const names = ['alex','deven','carry','milan','david']

console.log(names.includes('deven'))

// Output : true

Important: In JavaScript, includes() method is case sensitive.That means if the name ‘deven’ is in the UpperCase form like ‘DEVEN’ then it will return false. Though the name is still contained in the array. See the code below:

const names = ['alex','DEVEN','carry','milan','david']

console.log(names.includes('deven'))

// Output : false

To avoid this unwanted situation you can simply use map() and make case insensitive. See the solution code below:

const names = ['alex','DEVEN','carry','milan','david']

const caseInsensitiveNames = names.map(el => el.toLowerCase())

console.log(caseInsensitiveNames.includes('deven'))

// Output : true

This is all about array contains in JavaScript and you can get an overview from it.


Share on social media

//