Loading lesson path
Concept visual
Start at both ends
method searches an array for an element value and returns its position.
The first item has position 0, the second item has position 1, and so on.
Search an array for the item "Apple":
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple") + 1;
Syntax array.indexOf(item, start ) item Required. The item to search for. start Optional. Where to start the search. Negative values will start at the given position counting from the end, and search to the end.
Formula
Array.indexOf() returns - 1 if the item is not found.
If the item is present more than once, it returns the position of the first occurrence.Array.lastIndexOf() is the same as Array.indexOf(), but returns the position of the last occurrence of the specified element.
Search an array for the item "Apple":
const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.lastIndexOf("Apple") + 1;
Syntax array.lastIndexOf(item, start ) item Required. The item to search for start Optional. Where to start the search. Negative values will start at the given position counting from the end, and search to the beginning
Array.includes() to arrays. This allows us to check if an element is present in an array (including NaN, unlike indexOf).
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Mango"); // is true
Syntax array.includes(Formula
search - item) Array.includes() allows to check for NaN values. Unlike Array.indexOf().