PASSWORD RESET

Your destination for complete Tech news

How to check if an array includes a value in JavaScript?

404 0
< 1 min read

To check if an array includes a value in JavaScript, you can use the includes method of the Array object. The includes method returns a boolean value indicating whether the array includes the specified value.

Here is an example of how to use the includes method to check if an array includes a value:

let arr = [1, 2, 3, 4, 5];

if (arr.includes(3)) {
  console.log('Array includes 3');
} else {
  console.log('Array does not include 3');
}

The includes method takes a single argument, which is the value to search for in the array. It returns true if the value is found in the array, and false if it is not found.

You can also use the includes method to check if an array includes a value at a specific index by passing a second argument to specify the index to start the search from. For example:

let arr = [1, 2, 3, 4, 5];

if (arr.includes(3, 2)) {
  console.log('Array includes 3 at index 2 or higher');
} else {
  console.log('Array does not include 3 at index 2 or higher');
}

The includes method is supported in modern browsers, and it is also available in Node.js. If you need to support older browsers or environments that do not have the includes method, you can use the indexOf method to check if an array includes a value. The indexOf method returns the index of the value in the array, or -1 if the value is not found.

let arr = [1, 2, 3, 4, 5];

if (arr.indexOf(3) !== -1) {
  console.log('Array includes 3');
} else {
  console.log('Array does not include 3');
}

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.