How to check if a specific value or an element is present in an array in JavaScript?

Published December 1, 2021

To check if a specific value or an element is present in an array, you can use the includes() method on the array in JavaScript.

TL;DR

// a simple array of numbers
const nums = [100, 200, 300, 400];

// check if value "300" is present
// in the `nums` array
// using the includes() method
nums.includes(300); // true

// check if value "1000" is present
// in the `nums` array
// using the includes() method
nums.includes(1000); // false

For example, let's say we have an array called nums with values of 100, 200, 300 and, 400 like this,

// a simple array of numbers
const nums = [100, 200, 300, 400];

Now to check if a value or an element 300 is present on the array, we can use the includes() method on the nums array:

  • and pass the value we need to search within the array as an argument to the method, in our case, it is the value 300.
  • the method will return a boolean value true if present and false if it is not present in the array.

it can be done like this,

// a simple array of numbers
const nums = [100, 200, 300, 400];

// check if value "300" is present
// in the `nums` array
// using the includes() method
nums.includes(300); // true

As you can see that the includes() method returned boolean value true indicating that the value is present in the array.

Let's also try to search for a number that is not present in the array, say 1000 like this,

// a simple array of numbers
const nums = [100, 200, 300, 400];

// check if value "300" is present
// in the `nums` array
// using the includes() method
nums.includes(300); // true

// check if value "1000" is present
// in the `nums` array
// using the includes() method
nums.includes(1000); // false

As you can see from the above output that searching for the value 1000 returned a boolean value of false indicating it is not present in the nums array.

See the above code live in JSBin.

That's all 😃!

Feel free to share if you found this useful 😃.


Share on: Facebook Twitter