javascript
  1. javascript-indexof

JavaScript indexOf()

The indexOf() method in JavaScript is used to search for a specified value in an array or string. It returns the index of the first occurrence of the specified value, or -1 if the value is not found.

Syntax

array.indexOf(searchValue, fromIndex)
string.indexOf(searchValue, fromIndex)

Parameters:

  • searchValue: The value to search for in the array or string.
  • fromIndex (optional): The index to start the search from. If not specified, fromIndex defaults to 0 for both arrays and strings.

Example

const array = [2, 4, 6, 8, 10];
console.log(array.indexOf(6)); // Output: 2

const string = 'Hello, world!';
console.log(string.indexOf('world')); // Output: 7

Output

The output of the above code will be:

2
7

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IndexOf Example</title>
</head>
<body>

<script>
    // Array example
    const array = [2, 4, 6, 8, 10];

    // Log the index of 6 in the array
    document.write("<p>Index of 6 in the array: " + array.indexOf(6) + "</p>");

    // String example
    const string = 'Hello, world!';

    // Log the index of 'world' in the string
    document.write("<p>Index of 'world' in the string: " + string.indexOf('world') + "</p>");
</script>

</body>
</html>

Try Playground

Explanation

In the above example, the indexOf() method is used to search for the value 6 in the array array and the value world in the string string. The method returns the index of the first occurrence of the specified value (6 at index 2 in array and world at index 7 in string).

If the value is not found in the array or string, the method returns -1.

Use

The indexOf() method is commonly used to check if a value exists in an array or string. It can also be used to get the index of the first occurrence of a value in an or string.

Important Points

  • The indexOf() method is case sensitive.
  • If the searchValue parameter is an object, the method will search for references to that object in the array or string.
  • The fromIndex parameter must be a number. If it is not, the method will try to convert it to a number before searching.
  • indexOf() returns -1 if the searchValue is not found in the array or string.

Summary

The indexOf() method is a useful method in JavaScript for searching for a specified value in an array or string. It returns the index of the first occurrence of the specified value, or -1 if the value is not found. It is commonly used to check if a value exists in an array or string and to get the index of the first occurrence of a value in an array or string.

Published on: