Lecture
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.
Lessons in this chapter ยท Basic JavaScript Syntax
- 1. Object
- 2. Fill-in-the-blank quiz
- 3. Functions
- 4. Advanced Features of Functions
- 5. Arrow Functions
- 6. Method
- 7. Multiple-choice quiz
- 8. Date Object
- 9. Math Object
- 10. Array
- 11. Array Method - Slice
- 12. Array Methods - indexOf, lastIndexOf, includes
- 13. Array Methods - push, pop, unshift, shift
- 14. Array Methods - forEach, map, filter, find
- 15. Array Method - Sort
- 16. Fill-in-the-blank quiz
Quiz
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