How to Use indexOf in JavaScript: Syntax and Examples
In JavaScript,
indexOf is a method used to find the position of a substring in a string or an element in an array. It returns the first index where the item is found or -1 if it is not present.Syntax
The indexOf method can be used on strings and arrays with the following syntax:
- For strings:
string.indexOf(searchValue, fromIndex) - For arrays:
array.indexOf(searchElement, fromIndex)
searchValue/searchElement: The item to find.
fromIndex (optional): The position to start searching from (default is 0).
javascript
const str = 'hello world'; const index = str.indexOf('world', 0); const arr = [10, 20, 30, 20]; const idx = arr.indexOf(20, 1);
Example
This example shows how to find the position of a substring in a string and an element in an array using indexOf. It also shows what happens when the item is not found.
javascript
const text = 'I love JavaScript'; const pos1 = text.indexOf('love'); const pos2 = text.indexOf('Python'); const numbers = [5, 10, 15, 20]; const pos3 = numbers.indexOf(15); const pos4 = numbers.indexOf(25); console.log(pos1); // 2 console.log(pos2); // -1 console.log(pos3); // 2 console.log(pos4); // -1
Output
2
-1
2
-1
Common Pitfalls
One common mistake is not checking if indexOf returns -1, which means the item was not found. Using the result without this check can cause errors.
Also, indexOf is case-sensitive when used on strings, so searching for 'Love' instead of 'love' will fail.
javascript
const phrase = 'Hello World'; // Wrong: assuming the substring exists const pos = phrase.indexOf('world'); console.log(pos); // -1 (not found, but might be unexpected) // Right: check before using if (phrase.indexOf('world') !== -1) { console.log('Found!'); } else { console.log('Not found'); } // Case sensitivity example console.log(phrase.indexOf('World')); // 6 console.log(phrase.indexOf('world')); // -1
Output
-1
Not found
6
-1
Quick Reference
| Method | Description | Returns |
|---|---|---|
| string.indexOf(searchValue, fromIndex) | Finds substring position in string | Index or -1 if not found |
| array.indexOf(searchElement, fromIndex) | Finds element position in array | Index or -1 if not found |
| fromIndex (optional) | Start searching from this index | Defaults to 0 |
Key Takeaways
Use
indexOf to find the first position of a substring or element in strings and arrays.If the item is not found,
indexOf returns -1.Always check for
-1 before using the result to avoid errors.Remember that
indexOf is case-sensitive when used on strings.You can specify a starting index to begin the search with the optional second argument.