IndexOf vs includes in JavaScript: Key Differences and Usage
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.
| Feature | indexOf | includes |
|---|---|---|
| Return Type | Number (index or -1) | Boolean (true or false) |
| Purpose | Find position of element | Check if element exists |
| Works On | Strings and arrays | Strings and arrays |
| Case Sensitivity | Case-sensitive | Case-sensitive |
| Introduced In | Early JavaScript versions | ES6 (2015) |
| Use for | Finding index or existence | Simple 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
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"); }
includes Equivalent
const fruits = ['apple', 'banana', 'cherry']; // Check if 'banana' exists if (fruits.includes('banana')) { console.log("Found 'banana'"); } else { console.log("'banana' not found"); }
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.includes for simple presence checks and indexOf when you need the element's location.