- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Arrays
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- Else
- Else if
- Enum
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- includes()
- Infinity property
- Iterator
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Object.keys()
- Overriding methods
- Parameters
- Promises
- Random
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- String concat()
- String indexOf()
- Substring
- Switch statement
- Template literals
- Ternary operator
- Title
- Type conversion
- While loop
JAVASCRIPT
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.
Quick Answer: How to Use indexOf()
in JS
The indexOf()
method finds the first index of a specified element in an array. If the element is not found in the array, it returns -1
. This is most commonly used to check if an element exists or to get its position.
Syntax:
array.indexOf(searchElement)
Example:
const fruits = ['apple', 'banana', 'orange'];
// Find the index of 'banana'
console.log(fruits.indexOf('banana')); // Output: 1
// Check for an element that doesn't exist
console.log(fruits.indexOf('grape')); // Output: -1
// A common way to check for existence
if (fruits.indexOf('apple') !== -1) {
console.log('Apple exists!');
}
How to Use JavaScript Array indexOf
Here’s the basic syntax:
array.indexOf(searchElement, fromIndex)
searchElement
: The item to search for in the array.fromIndex
: Optional. The index to start searching from. Default is0
.
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
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
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
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
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
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
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:
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:
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:
const frameworks = ["React", "Vue", "Angular"];
console.log(frameworks.indexOf("react")); // -1
Normalize the strings if needed:
frameworks.map(f => f.toLowerCase()).indexOf("react"); // 0
Combine with Conditional Logic
const permissions = ["read", "write"];
if (permissions.indexOf("write") !== -1) {
enableEditing();
}
Create utility functions to reuse logic:
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:
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:
const items = [{ id: 1 }, { id: 2 }];
console.log(items.indexOf({ id: 1 })); // -1
Use findIndex()
when working with objects:
const idx = items.findIndex(item => item.id === 1); // 0
Remove Items by Value Using indexOf
Find the position first, then remove it with splice()
:
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:
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.
Key Takeaways for JavaScript indexOf()
- Returns an Index or -1:
indexOf()
returns the first index of an element. If the element doesn't exist, it returns1
. - Used for Existence Checks: A common pattern is
if (arr.indexOf(item) !== -1)
to check if an item is in an array. - Strict Equality (
===
): It uses strict comparison, meaningindexOf(1)
will not match the string"1"
. It is also case-sensitive. - Only Finds the First Match: If an array has duplicate elements,
indexOf()
will only return the index of the first one it finds. - Not for Objects: It does not work for finding objects unless you have a direct reference to that object. Use
findIndex()
for searching arrays of objects based on their properties. includes()
is fortrue
/false
: If you only need to know if an element exists and don't need its position,array.includes()
provides a more readabletrue
/false
result.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.