Hey There 👋
Welcome to Episode 5 of my Array Methods Explain Show.
as always, if you are here then i suppose you must have pre knowledge of javascript and arrays.
we will be discussing only one method on this episode which is : INDEXOF
The indexOf method returns the first index at which a given element can be found in the array, or -1 if it is not present.
the syntax of indexOf method is :
- item : the item whose index is to be searched in given array
- fromIndex (optional) : The index from which the search should start. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched. If fromIndex value is a negative number, it is taken as the offset from the end of the array. If the provided index is 0, then the whole array will be searched that’s why the default value is also 0.
Now, lets look at examples :
- finding index of element
let colors = ["Red", "Blue", "Yellow", "White", "Black"];
let value = colors.indexOf("Yellow"); // returns the index of Yellow
console.log(value); // 2
- finding index of element from given positive Index
let colors = ["Yellow", "Blue", "Yellow", "White", "Black"];
let value = colors.indexOf("Yellow", 1); // returns the index of Yellow starting from index 1
console.log(value); // 2
- finding index of element from given negative Index
let colors = ["Yellow", "Blue", "Yellow", "White", "Black"];
let value = colors.indexOf("Black", -3); // returns the index of Black starting from 3rd last index
console.log(value); // 4
- finding index of element that is not in array
let colors = ["Yellow", "Blue", "Yellow", "White", "Black"];
let value = colors.indexOf("Grey"); // returns -1 because grey is not in array
console.log(value); // -1
One thing to note regarding indexOf is that it the elements of array are always compared with strict equality (i.e === is used while comparing)
Top comments (0)