Skip to content

JavaScript array includes method | check if a value exists

  • by

JavaScript array includes is used to check an element is exists in the array or not. It’s an inbuilt function and returns true if the element is present in Array.

Syntax

array.includes(element, start)

Parameter

  • element:- A element value want to search.
  • start:- Array position to start the search given element. Optional and the default value is 0.

Return values

It return a Boolean value True if value found otherwise return False.

Example of JavaScript array includes a method

Let’s see example code to check if an array includes “A”:

<!DOCTYPE html>
<html>
  <head>
    <script>

    	var alpha = ["B", "A", "C", "D"];
		var n = alpha.includes("A");
        alert(n)

    </script>
  </head>   

</html>

Output:

JavaScript array includes method

Another Example

Let’s set the starting position at 3. The output will be false because after 1 portion there is no value “A”.

<!DOCTYPE html>
<html>
  <head>
    <script>

    	var alpha = ["B", "A", "C", "D"];
		var n = alpha.includes("A",3);
        alert(n)

    </script>
  </head>   

</html>

Output:

 check if a value exists in array javascript

Q: How to check if a value exists in array javascript?

Answer: ECMAScript 2016 incorporates an includes() method for arrays that specifically solves the problem, and so is now the preferred method.

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(1, 2);  // false (second parameter is the index position in this array at which to begin searching)

Note: that this returns false if the item in the array is an object. This is because similar objects are two different objects in JavaScript.

Do comment if you have any doubts and suggestion on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *