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.
Mission
0 / 1
What is the most appropriate thing to fill in the blank below?
The method used to check if a specific element is included in an array is .
indexOf()
lastIndexOf()
includes()
find()
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Execution Result