TypeScript Array indexOf()
Syntax & Examples


Array.indexOf() method

The indexOf() method returns the index of the first occurrence of a specified value in an array, or -1 if it is not present. The array is searched from the beginning to the end, starting at fromIndex.


Syntax of Array.indexOf()

The syntax of Array.indexOf() method is:

indexOf(searchElement: T, fromIndex?: number): number

This indexOf() method of Array returns the index of the first occurrence of a value in an array.

Parameters

ParameterOptional/RequiredDescription
searchElementrequiredThe element to locate in the array.
fromIndexoptionalThe index at which to start searching. Defaults to 0. If the index is greater than or equal to the array's length, -1 is returned, meaning the array will not be searched. If the provided index is a negative number, it is taken as the offset from the end of the array.

Return Type

Array.indexOf() returns value of type number.



✐ Examples

1 Using indexOf() to find the first occurrence of a number

The indexOf() method can be used to find the index of the first occurrence of a number in an array.

For example,

  1. Create an array arr with numeric values [1, 2, 3, 1, 2, 3].
  2. Use indexOf(2) to find the first occurrence of the number 2 in the array.
  3. Store the result in index.
  4. Log index to the console.

TypeScript Program

const arr = [1, 2, 3, 1, 2, 3];
const index = arr.indexOf(2);
console.log(index);

Output

1

2 Using indexOf() to find the first occurrence of a string

The indexOf() method can be used to find the index of the first occurrence of a string in an array.

For example,

  1. Create an array arr with string values ['apple', 'banana', 'cherry', 'apple'].
  2. Use indexOf('apple') to find the first occurrence of the string 'apple' in the array.
  3. Store the result in index.
  4. Log index to the console.

TypeScript Program

const arr = ['apple', 'banana', 'cherry', 'apple'];
const index = arr.indexOf('apple');
console.log(index);

Output

0

3 Using indexOf() with a fromIndex parameter

The indexOf() method can be used with a fromIndex parameter to start the search from a specific index.

For example,

  1. Create an array arr with numeric values [1, 2, 3, 1, 2, 3].
  2. Use indexOf(2, 3) to find the first occurrence of the number 2 in the array, starting the search from index 3.
  3. Store the result in index.
  4. Log index to the console.

TypeScript Program

const arr = [1, 2, 3, 1, 2, 3];
const index = arr.indexOf(2, 3);
console.log(index);

Output

4

Summary

In this TypeScript tutorial, we learned about indexOf() method of Array: the syntax and few working examples with output and detailed explanation for each example.