indexOf()
The indexof()
method returns the first index of the element found in the array. It returns a value of -1
if the element is not found. This method is helpful when you want to check if a given element is present in an array.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let numberIndex = numbers.indexOf(5);
console.log(numberIndex); // 4
If the element is not present, the method returns -1
.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let numberIndex = numbers.indexOf(35);
console.log(numberIndex); // -1
Similarly, let us look at an example containing an array of strings.
let strings = ["One", "Two", "Three", "Four", "Five"];
let searchIndex = strings.indexOf("Two");
console.log(searchIndex); // 1
Note, the indexOf()
looks for the exact value. Hence, it will not work if the string is case-sensitive.
let strings = ["One", "Two", "Three", "Four", "Five"];
let searchIndex = strings.indexOf("two");
console.log(searchIndex); // -1
lastIndexOf()
The lastIndexOf()
method is similar to the indexOf()
method except it returns the last index of the element found in a given array. It returns a -1
if the element is not present in the array.
let strings = ["One", "Two", "Three", "Four", "Five", "Two"];
let searchIndex = strings.lastIndexOf("Two");
console.log(searchIndex); // 5