JavaScript Array indexOf: Syntax, Usage, and Examples
The indexOf()
method lets you search an array for a specific value and returns its first index. If the value isn’t found, it returns -1
. The JavaScript array indexOf method is a quick and reliable way to determine the position of an element in an array, especially when working with primitive types like numbers and strings.
How to Use JavaScript Array indexOf
Here’s the basic syntax:
jsx
array.indexOf(searchElement, fromIndex)
searchElement
: The item to search for in the array.fromIndex
: Optional. The index to start searching from. Default is0
.
jsx
const animals = ["cat", "dog", "rabbit", "dog"];
console.log(animals.indexOf("dog")); // Output: 1
The method finds the first "dog"
in the array and returns its index.
When to Use Array indexOf JavaScript
Apply the array indexOf JavaScript method when you need to:
Find the Index of an Item
jsx
const tools = ["hammer", "screwdriver", "wrench"];
const index = tools.indexOf("wrench"); // 2
Quickly locating a value helps with both lookups and conditional logic.
Verify That a Value Exists
jsx
const tags = ["sale", "new", "featured"];
if (tags.indexOf("sale") !== -1) {
console.log("Show sale badge");
}
You don’t need a loop or manual comparison—just check if the result is -1
.
Run Logic Based on Array Content
jsx
const roles = ["user", "admin", "editor"];
if (roles.indexOf("admin") >= 0) {
grantAdminAccess();
}
This avoids writing multiple if
statements and keeps the check compact.
Examples of JavaScript Array indexOf in Action
Use with Numbers
jsx
const ages = [18, 21, 30, 18];
console.log(ages.indexOf(18)); // 0
console.log(ages.indexOf(99)); // -1
Only the first match gets returned, even if duplicates exist.
Use with Strings
jsx
const colors = ["red", "blue", "green", "blue"];
console.log(colors.indexOf("blue")); // 1
Even with repeats, the method stops at the first match.
Start Search from a Specific Index
jsx
const letters = ["a", "b", "c", "b", "a"];
console.log(letters.indexOf("b", 2)); // 3
By setting a fromIndex
, you skip earlier matches.
Learn More About indexOf in JavaScript Array
Understand How indexOf Compares Values
The comparison uses strict equality (===
). That means types must match:
jsx
const list = [1, "1", true];
console.log(list.indexOf(1)); // 0
console.log(list.indexOf("1")); // 1
console.log(list.indexOf(true)); // 2
Mismatched types—even if visually similar—don’t count as matches.
Handle Duplicates Carefully
Even if an array contains multiple matches, indexOf()
will only find the first:
jsx
const cities = ["Paris", "Rome", "Paris"];
console.log(cities.indexOf("Paris")); // 0
To find additional matches, use a loop or the filter()
method.
Deal with Case Sensitivity
The method is case-sensitive:
jsx
const frameworks = ["React", "Vue", "Angular"];
console.log(frameworks.indexOf("react")); // -1
Normalize the strings if needed:
jsx
frameworks.map(f => f.toLowerCase()).indexOf("react"); // 0
Combine with Conditional Logic
jsx
const permissions = ["read", "write"];
if (permissions.indexOf("write") !== -1) {
enableEditing();
}
Create utility functions to reuse logic:
jsx
function contains(arr, val) {
return arr.indexOf(val) !== -1;
}
Use that helper to simplify checks across your code.
Compare indexOf and includes()
Use includes()
for readability when you don’t need the index:
jsx
const tech = ["JavaScript", "HTML", "CSS"];
tech.includes("HTML"); // true
Still, if the position matters, stick with indexOf()
.
Don’t Expect indexOf to Work on Objects
Searching for objects or arrays with indexOf won’t work unless they match by reference:
jsx
const items = [{ id: 1 }, { id: 2 }];
console.log(items.indexOf({ id: 1 })); // -1
Use findIndex()
when working with objects:
jsx
const idx = items.findIndex(item => item.id === 1); // 0
Remove Items by Value Using indexOf
Find the position first, then remove it with splice()
:
jsx
const animals = ["cat", "dog", "bird"];
const remove = "dog";
const i = animals.indexOf(remove);
if (i !== -1) {
animals.splice(i, 1);
}
You can apply this pattern to filter dynamic input or user-generated content.
Work with indexOf Inside Loops
Detect and skip duplicate values using the index:
jsx
const names = ["Alice", "Bob", "Alice", "Eve"];
names.forEach((name, idx) => {
if (names.indexOf(name) === idx) {
console.log(`Unique: ${name}`);
}
});
This keeps only the first occurrence of each item.
The indexOf()
method gives you a clean way to locate values inside arrays. It’s fast, works well with simple data, and pairs nicely with other array methods like splice()
or filter()
. Whether you’re validating form inputs, managing lists, or checking for duplicates, using array indexOf JavaScript functionality keeps your code readable and concise.