Difference Between JavaScript Includes() vs. IndexOf() Array Method

Welcome to the ultimate guide on comparing the JavaScript includes() and indexOf() array methods! This guide will help you understand the differences between these two methods in a simple, fun, and easy-to-understand way. Whether you’re just starting with JavaScript or looking to brush up on your skills, this guide is perfect for you. Let’s dive in!

Introduction to Arrays

Before we get into the details of includes() and indexOf(), let’s quickly review what an array is. An array is a special variable in JavaScript that can hold more than one value at a time. Think of it like a list of items you want to keep together.

Here’s an example of an array:

JavaScript
let fruits = ['apple', 'banana', 'orange'];

In this array, we have three items: 'apple', 'banana', and 'orange'.

What is the includes() Method?

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate. It is case-sensitive and checks for the exact match of the value.

Example of includes()

JavaScript
let fruits = ['apple', 'banana', 'orange'];
let hasBanana = fruits.includes('banana');
console.log(hasBanana); // true

In this example, the includes() method checks if 'banana' is in the fruits array.

What is the indexOf() Method?

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present. It is also case-sensitive and checks for the exact match of the value.

Example of indexOf()

JavaScript
let fruits = ['apple', 'banana', 'orange'];
let bananaIndex = fruits.indexOf('banana');
console.log(bananaIndex); // 1

In this example, the indexOf() method finds the index of 'banana' in the fruits array.

Key Differences Between includes() and indexOf()

To help you understand the differences better, let’s look at a table that compares the key features of the includes() and indexOf() methods.

Featureincludes()indexOf()
PurposeChecks if an array contains a certain valueFinds the first index of a given element
Returnstrue or falseIndex of the element or -1
Case SensitivityYesYes
Modifies ArrayNoNo
Syntaxarray.includes(value)array.indexOf(value)
UsageWhen you need to know if a value exists in an arrayWhen you need to find the position of a value
Examplefruits.includes('banana')fruits.indexOf('banana')

Why Use includes()?

The includes() method is useful when you need to check if an array contains a certain value. Here are some scenarios:

  • Checking if a shopping list contains a specific item.
  • Verifying if a user has a specific role in an array of roles.
  • Determining if a keyword is present in a list of tags.

Why Use indexOf()?

The indexOf() method is useful when you need to find the position of a specific value in an array. Here are some scenarios:

  • Finding the position of a specific item in a list.
  • Checking the index of a user’s role in an array of roles.
  • Locating the first occurrence of a keyword in a list of tags.

How to Use includes() and indexOf() Together

Using includes() and indexOf() together can be very effective in managing arrays. Let’s look at an example where we use both methods.

Example: Managing a To-Do List

JavaScript
let toDoList = ["buy groceries", "clean the house", "pay bills"];

// Check if 'clean the house' is in the list
let hasCleanTask = toDoList.includes("clean the house");
console.log("Task present:", hasCleanTask); // true

// Find the index of 'pay bills'
let payBillsIndex = toDoList.indexOf("pay bills");
console.log("Index of pay bills:", payBillsIndex); // 2

In this example, we use includes() to check if 'clean the house' is in the to-do list and indexOf() to find the index of 'pay bills'.

Detailed Examples and Use Cases

Example 1: Checking for a Value with includes()

JavaScript
let numbers = [10, 20, 30, 40, 50];
let hasThirty = numbers.includes(30);
console.log(hasThirty); // true

In this example, the includes() method checks if 30 is in the numbers array.

Example 2: Finding the Index of a Value with indexOf()

JavaScript
let numbers = [10, 20, 30, 40, 50];
let indexThirty = numbers.indexOf(30);
console.log(indexThirty); // 2

In this example, the indexOf() method finds the index of 30 in the numbers array.

Example 3: Using includes() and indexOf() in a Shopping List

JavaScript
let shoppingList = ["milk", "bread", "eggs", "butter"];

// Check if 'bread' is in the list
let hasBread = shoppingList.includes("bread");
console.log("Bread in list:", hasBread); // true

// Find the index of 'eggs'
let eggsIndex = shoppingList.indexOf("eggs");
console.log("Index of eggs:", eggsIndex); // 2

In this example, we use includes() to check if 'bread' is in the shopping list and indexOf() to find the index of 'eggs'.

Common Mistakes and How to Avoid Them

While using includes() and indexOf() is straightforward, there are some common mistakes to watch out for:

  1. Case Sensitivity: Both methods are case-sensitive, so ensure the value matches exactly, including the case.
JavaScript
let fruits = ["Apple", "Banana", "Orange"];
console.log(fruits.includes("apple")); // false
console.log(fruits.indexOf("apple")); // -1
  1. Using indexOf() with Objects: indexOf() compares by strict equality, which may not work as expected with objects.
JavaScript
let objects = [{ a: 1 }, { a: 2 }];
let index = objects.indexOf({ a: 1 });
console.log(index); // -1, because objects are different references
  1. Expecting includes() and indexOf() to Modify the Array: Remember that these methods only return a value and do not change the original array.
JavaScript
let items = [1, 2, 3, 4, 5];
let found = items.includes(3);
console.log(items); // [1, 2, 3, 4, 5]
console.log(found); // true

When to Use includes() and indexOf()

Understanding when to use includes() and indexOf() can help you manage your arrays effectively:

  • Use includes():
  • When you need to check if an array contains a specific value.
  • In scenarios like checking if a shopping list contains a specific item, verifying if a user has a specific role, or determining if a keyword is present in a list of tags.
  • Use indexOf():
  • When you need to find the index of a specific value in an array.
  • In scenarios like finding the position of a specific item in a list, checking the index of a user’s role in an array of roles, or locating the first occurrence of a keyword in a list of tags.

Conclusion

The JavaScript includes() and indexOf() methods are essential tools for managing arrays. By understanding their differences and knowing when and how to use them, you can create more dynamic and efficient code.

This guide has covered the basics of includes() and indexOf(), provided practical examples, and highlighted common mistakes to avoid. Whether you’re checking for the presence of values, locating indices, or managing lists, these methods will help you keep your code organized and functional.

Remember to experiment with the examples and adapt them to your needs. Happy coding!


Leave a Reply