Skip to main content
Practice

Array Methods - indexOf, lastIndexOf, includes

Let's explore methods used to find a specific element in an array.


indexOf

Finds a specific element in an array and returns its index. If the element is not found, -1 is returned.

Example of indexOf() Method
const fruits = ['Apple', 'Banana', 'Cherry', 'Apple'];
const index = fruits.indexOf('Apple');

console.log(index); // 0

In the example above, "Apple" is at index 0 in the array, so 0 is printed.


lastIndexOf

Finds the last occurrence of a specific element in an array and returns its index. If the element is not found, -1 is returned.

Example of lastIndexOf() Method
const fruits = ['Apple', 'Banana', 'Cherry', 'Apple'];
const lastIndex = fruits.lastIndexOf('Apple');

console.log(lastIndex); // 3

"Apple" last appears at index 3 in the array, so 3 is printed.


includes

Checks whether a specific element exists in an array. Returns true if it exists, otherwise false.

Example of includes() Method
const fruits = ['Apple', 'Banana', 'Cherry'];
const hasApple = fruits.includes('Apple');

console.log(hasApple); // true

In the example above, since the array contains "Apple", true is printed.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.