What is the array.indexOf() method in TypeScript?

Overview

The indexOf() method is used to return the index position of the first match of a value in an array in TypeScript, as well as in JavaScript. This method returns an integer value. However, if the element does not exist in the array, then the method returns -1.

Syntax

array.indexOf(element)
Syntax of the "indexOf()" method in TypeScript

Parameter value

element: This is the element whose index we want to get.

Return value

The index of the first matching element, which is an integer, in the array is returned. If no such element exists, then a -1 integer value is returned.

Example

// create arrays in TypeScript
let names: string[] = ["Theodore", "James", "Peter", "Amaka"]
let numbers : Array<number>;
numbers = [12, 34, 5, 0.9]
let cars : Array<string> = ["Porsche", "Toyota", "Lexus"]
// get and print index of some elements
console.log(names.indexOf("Theodore"))
console.log(names.indexOf("James"))
console.log(numbers.indexOf(10000))
console.log(numbers.indexOf(0.9))
console.log(cars.indexOf("TOYOTA"))

Explanation

  • Lines 2–5: We create some arrays in TypeScript.
  • Lines 8–12: We get the index of some elements that exist and some that do not exist. Then, we print the results to the console.
Note: In line 12, the method returns -1 because "TOYOTA" is not present in the array "Toyota".

Free Resources