ArticleZip > Array Prototype Includes Vs Array Prototype Indexof

Array Prototype Includes Vs Array Prototype Indexof

When working with arrays in JavaScript, two important methods to understand and use are `Array.prototype.includes()` and `Array.prototype.indexOf()`. While both these methods operate on arrays, they have different functionalities that can be beneficial based on what you're trying to achieve in your code.

Let's break down the differences between `Array.prototype.includes()` and `Array.prototype.indexOf()` to help you better understand how each one works and when to use them.

**Array.prototype.includes()**

The `Array.prototype.includes()` method is used to check if an array includes a certain element or value. It returns `true` if the element is found in the array and `false` if it is not. This method simplifies the process of checking for the presence of an element without the need to specify the index where it is located.

Here's a simple example of how to use `Array.prototype.includes()`:

Javascript

const fruits = ['apple', 'banana', 'kiwi', 'orange'];

console.log(fruits.includes('banana')); // Output: true
console.log(fruits.includes('grape')); // Output: false

In this example, `fruits.includes('banana')` returns `true` because the 'banana' element is present in the `fruits` array, while `fruits.includes('grape')` returns `false` since 'grape' is not in the array.

**Array.prototype.indexOf()**

On the other hand, the `Array.prototype.indexOf()` method is used to find the first occurrence of a specified value within an array. If the value is found, it returns the index of that value; otherwise, it returns -1.

Let's illustrate the usage of `Array.prototype.indexOf()` with an example:

Javascript

const numbers = [10, 20, 30, 40, 50];

console.log(numbers.indexOf(30)); // Output: 2
console.log(numbers.indexOf(60)); // Output: -1

In this snippet, `numbers.indexOf(30)` returns 2 since '30' appears at index 2 in the `numbers` array, while `numbers.indexOf(60)` returns -1 as '60' is not a part of the array.

**When to Use Each Method**

- Use `Array.prototype.includes()` when you need to check if an array contains a specific element.
- Use `Array.prototype.indexOf()` when you want to find the index of a specific element within an array or check if the element exists in the array.

In summary, `Array.prototype.includes()` is great for simple existence checks, while `Array.prototype.indexOf()` is useful when you need to know the exact position of an element within an array.

By understanding the distinctions between `Array.prototype.includes()` and `Array.prototype.indexOf()`, you can streamline your code and make more informed decisions when working with arrays in JavaScript. Remember to choose the method that best fits your specific requirements to optimize your coding experience.