Skip to content

JavaScript Array indexof method | find an element in array js

  • by

JavaScript Array indexof method searches the array for the specified element and returns its position. This method finds the index of the first occurrence of the search element provided as the argument to the function.

Syntax

array.indexOf(item, start)

Parameter Values

  • item: – An search element value (Required)
  • start:- Where to start the search. (Optional)

Return value

It returns the index of the first occurrence of the search Element. And returns -1 if the item is not found.

Example of javascript indexof array of objects

Let’s see the examples of how to find element in array js.

1. Find without position

Search an array for the item “A”:

<!DOCTYPE html>
<html>
    <head>
        <title> Example</title>
        <script type="text/javascript">
        	var fruits = ["B", "O", "A", "M"];
			var a = fruits.indexOf("A");
        	// show output in alert
        	alert(a)

        </script>
    </head>
    
</html>

Output:

javascript indexof array of objects

2. Start search after position

You can do start the search at the specified position, or at the beginning if no start position is specified, and end the search at the end of the array.

Search an array for the element “A”, starting the search at position 2:

<!DOCTYPE html>
<html>
    <head>
        <title> Example</title>
        <script type="text/javascript">
        	var fruits = ["A", "O", "A", "M", "B", "O", "A"];
			var a = fruits.indexOf("A", 2);
        	// show output in alert
        	alert(a)

        </script>
    </head>
    
</html>

Output:

javascript indexof array method

Do comment if you have any doubts and suggestions 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 *