W3docs

How to Check if an Element is Present in an Array in JavaScript?

Very often we need to check whether the element is in an array in JavaScript or not. In this snippet, we are going to learn some methods to do that.

An array is a data type that can hold multiple values in a single variable. It is an excellent solution if you have a list of different items and want to store them. Organizing elements also aids in searching. Knowing basic array operations is essential to improve your programming skills.

How to Create an Array

An array holds more than one value under a single name. Spaces and line breaks are not important while creating an array. Here are examples of JavaScript arrays:

JavaScript arrays

let arr1 = new Array();
let arr2 = [];

Javascript arrays

javascript— editable

Very often we need to check whether the element is in an array in JavaScript or not. In this snippet, we are going to learn some methods to do that.

First, we’ll look at a simple solution. We can check if an element is present in the array like this:

Javascript check element existence in array

javascript— editable

The loop traverses the array from index 0 to array.length - 1. We use the less-than operator (<) instead of less-than-or-equal (<=) to prevent an out-of-bounds error. Inside the if condition, we compare the target element with each array value. If they match, it prints "Element Found".

Next, we’ll use a flag variable to track whether the element is found.

Javascript check element existence in array

javascript— editable

If the element is found, the flag value changes inside the if condition, allowing us to determine its presence.

Now let’s consider another method of checking if the element is present in the array or not. It's the includes() method, which is now commonly used.

This method returns true if the array contains the specified element, and false if not, like this:

Javascript array includes method

javascript— editable

Let’s see another example:

Example

Javascript array includes code example

javascript— editable
Info

Note that includes() method is case sensitive.

Another useful method is indexOf(), which returns the index of the first occurrence of an element. It tells whether the array contains the given element or not. If the element is found, it returns its index. If not, indexOf() returns -1.

Here is an example:

Javascript indexOf example

javascript— editable

These two methods accept two parameters: searchElement and fromIndex. Let’s check them out:

ParameterDescription
searchElementRequired. The element to search for
fromIndexOptional. Default 0. The index to start the search from