JavaScript Array indexOf
Method (Live Playground)
The indexOf
method in JavaScript is used to find the first index at which a given element can be found in the array, or -1
if the element is not found.
Here is a simple example:
let colors = ['blue', 'red', 'green', 'yellow', 'red'];
let index = colors.indexOf('red');
console.log(index);
// Expected output: 1
In this example, indexOf("red")
finds the first occurrence of "red" in the colors
array and returns its index, which is 1
.
If the element is not found in the array, indexOf
returns -1
:
let colors = ['blue', 'green', 'yellow'];
let index = colors.indexOf('red');
console.log(index);
// Expected output: -1
In this example, since "red" is not in the colors
array, indexOf("red")
returns -1
.
You can also specify a second parameter to indicate the index to start the search from:
let colors = ['blue', 'red', 'green', 'yellow', 'red'];
let index = colors.indexOf('red', 2);
console.log(index);
// Expected output: 4
In this example, indexOf("red", 2)
starts searching for "red" from index 2
. Therefore, it finds the "red" at index 4
, not the one at index 1
.
In conclusion, the indexOf
method in JavaScript is a helpful way to find the position of elements in an array. It is a beneficial tool when you need to locate the existence and position of specific items in your array.
Experiment with indexOf
on your own to fully understand its usage!