includes with array in js
Includes with Array in JavaScript
If you are working with arrays in JavaScript, you might have come across a situation where you need to check whether an element exists in an array or not. This is where the includes()
method comes in handy.
Using the includes() method
The includes()
method checks whether an element is present in an array or not and returns a boolean value. Here is an example:
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.includes('banana')); // true
console.log(fruits.includes('mango')); // false
In the above example, we have an array of fruits and we are using the includes()
method to check whether 'banana' and 'mango' are present in the array or not.
Using indexOf() method
The indexOf()
method can also be used to check whether an element exists in an array or not. The indexOf()
method returns the index of the first occurrence of the specified element in the array. If the element is not present, it returns -1. Here is an example:
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.indexOf('banana') !== -1); // true
console.log(fruits.indexOf('mango') !== -1); // false
In the above example, we are using the indexOf()
method to check whether 'banana' and 'mango' are present in the array or not. We are comparing the returned index value with -1 to get a boolean result.
Using a for loop
You can also use a for loop to check whether an element exists in an array or not. Here is an example:
const fruits = ['apple', 'banana', 'orange'];
let isPresent = false;
for (let i = 0; i < fruits.length; i++) {
if (fruits[i] === 'banana') {
isPresent = true;
break;
}
}
console.log(isPresent); // true
In the above example, we are using a for loop to iterate over the array and check whether 'banana' is present in the array or not. If it is present, we set the isPresent
variable to true and break out of the loop.
So, these are some of the ways to check whether an element exists in an array or not in JavaScript.