indexOf() - JavaScript Tutorial

indexOf()

BLUF: This tutorial on indexOf() provides an in-depth look at JavaScript's core features. It includes practical examples and code snippets to help you master modern JS development.
Key Discovery: indexOf()

Understanding indexOf() is crucial for building dynamic, interactive web applications. Explore the examples below to see it in action.

The indexOf method in JavaScript arrays serves the purpose of locating the index of a specific element within an array. It is important to note that this method is case-sensitive.

In an array, the index of the initial element consistently begins at zero. If a specified element cannot be found within the array, the function returns -1.

Syntax

The syntax for the indexOf method is outlined as follows:

Example

array.indexOf(element,index)

Parameter

element - This denotes the specific element that is to be located.

Return

An index of a particular element.

JavaScript Array indexOf method example

Let’s explore a few straightforward examples of the indexOf method.

Example 1

Here, we will print the position of an element.

Example

<script>

var arr=["C","C++","Python","C++","Java"];

var result= arr.indexOf("C++");

document.writeln(result);

</script>

Output:

Example 2

In this instance, we will specify the index position from which the search will commence.

Example

<script>

var arr=["C","C++","Python","C++","Java"];

var result= arr.indexOf("C++",2);

document.writeln(result);

</script>

Output:

Example 3

In this section, we will conduct a search for an element that does not exist within an array.

Example

<script>

var arr=["C","C++","Python","C++","Java"];

var result= arr.indexOf("JavaScript");

document.writeln(result);

</script>

Output:

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience