lastIndexOf() - JavaScript Tutorial

lastIndexOf()

BLUF: This tutorial on lastIndexOf() 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: lastIndexOf()

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

The lastIndexOf method in JavaScript arrays is utilized to locate the index of a specific element within an array. It functions similarly to the indexOf method, with the key distinction that it begins its search for the element from the end of the array.

The lastIndexOf function is sensitive to case distinctions. The index of the initial character in a string begins at zero. If a specified element cannot be found within a string, the method will return -1.

Syntax

The syntax for the lastIndexOf method is denoted as follows:

Example

array.lastIndexOf(element,index)

Parameter

element - It signifies the specific element that is to be located.

index - This denotes the starting position of the search index. It is not mandatory.

Return

An index of a particular element.

JavaScript Array lastIndexOf method example

Let's see some examples of lastIndexof method.

Example 1

Here, we will print the position of an element.

Example

<script>

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

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

document.writeln(result);

</script>

Output:

Example 2

In this illustration, we will specify the index position at which the search will commence.

Example

<script>

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

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

document.writeln(result);

</script>

Output:

Example 3

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

Example

<script>

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

var result= arr.lastIndexOf("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