0
0
JavascriptComparisonBeginner · 3 min read

IndexOf vs includes in JavaScript: Key Differences and Usage

In JavaScript, indexOf returns the position of a value in a string or array or -1 if not found, while includes returns a boolean indicating presence. Use includes for simple existence checks and indexOf when you need the exact position.
⚖️

Quick Comparison

Here is a quick side-by-side comparison of indexOf and includes methods in JavaScript.

FeatureindexOfincludes
Return TypeNumber (index or -1)Boolean (true or false)
PurposeFind position of elementCheck if element exists
Works OnStrings and arraysStrings and arrays
Case SensitivityCase-sensitiveCase-sensitive
Introduced InEarly JavaScript versionsES6 (2015)
Use forFinding index or existenceSimple existence check
⚖️

Key Differences

indexOf returns the index (position) of the first occurrence of a specified value in a string or array. If the value is not found, it returns -1. This means you can use it both to check if something exists and to know where it is.

includes, introduced in ES6, returns a simple true or false indicating whether the value exists anywhere in the string or array. It does not provide the position.

Because includes returns a boolean, it is often clearer and easier to read when you only need to know if a value is present. indexOf requires checking if the result is not -1 to confirm presence, which can be less intuitive.

⚖️

Code Comparison

javascript
const fruits = ['apple', 'banana', 'cherry'];

// Check if 'banana' exists and get its index
const index = fruits.indexOf('banana');
if (index !== -1) {
  console.log(`Found 'banana' at index ${index}`);
} else {
  console.log("'banana' not found");
}
Output
Found 'banana' at index 1
↔️

includes Equivalent

javascript
const fruits = ['apple', 'banana', 'cherry'];

// Check if 'banana' exists
if (fruits.includes('banana')) {
  console.log("Found 'banana'");
} else {
  console.log("'banana' not found");
}
Output
Found 'banana'
🎯

When to Use Which

Choose includes when you only need to know if a value exists in a string or array because it is simpler and more readable.

Choose indexOf when you need to find the exact position of the value or want to perform operations based on the index.

For example, use indexOf if you want to replace or remove an element at a specific position.

Key Takeaways

includes returns a boolean, making it clearer for existence checks.
indexOf returns the index or -1, useful for position-based logic.
includes was introduced in ES6; indexOf is older and widely supported.
Use includes for simple presence checks and indexOf when you need the element's location.