Array Methods - indexOf, lastIndexOf, includes
Let's explore methods to find a specific element in an array.
indexOf()
This method returns the index of the first occurrence of a specified element in the array. If the element is not found, it returns -1
.
indexOf() Method Example
const fruits = ['Apple', 'Banana', 'Cherry', 'Apple'];
const index = fruits.indexOf('Apple');
console.log(index); // 0
In the example above, "Apple" is found at index 0, so the method returns 0
.
lastIndexOf()
This method returns the index of the last occurrence of a specified element in the array. If the element is not found, it returns -1
.
lastIndexOf() Method Example
const fruits = ['Apple', 'Banana', 'Cherry', 'Apple'];
const lastIndex = fruits.lastIndexOf('Apple');
console.log(lastIndex); // 3
"Apple" is found at index 3 when counting from the end, so the method returns 3
.
includes()
This method checks if a specified element is present in the array. It returns true
if the element is found and false
otherwise.
includes() Method Example
const fruits = ['Apple', 'Banana', 'Cherry'];
const hasApple = fruits.includes('Apple');
console.log(hasApple); // true
In this example, the array contains "Apple", so the method returns true
.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.