Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
The includes()
method is a built-in method for arrays in JavaScript. It is used to check if an array contains a specific value, and it returns a Boolean value (true or false) indicating whether the value is found in the array.
In this deep dive, we'll explore the includes()
method in detail, along with its usage and options.
javascriptarray.includes(searchElement, fromIndex);
array: The array you want to search within.
searchElement: The element you want to check for within the array.
fromIndex (optional): The index at which the search begins. If provided, the search starts from this index. If not provided, the search starts from the beginning of the array.
The includes()
method returns true if the searchElement is found in the array; otherwise, it returns false.
1. Basic Usage:
javascriptconst fruits = ['apple', 'banana', 'cherry'];
const hasCherry = fruits.includes('cherry');
console.log(hasCherry); // Outputs: true
In this example, the includes()
method is used to check if the array fruits contains the value 'cherry', and it returns true.
2. Searching from a Specific Index:
javascriptconst numbers = [1, 2, 3, 4, 5];
const includesThree = numbers.includes(3, 2);
console.log(includesThree); // Outputs: true
Here, the includes()
method is used to search for the value 3 starting from the index 2, and it returns true.
3. Checking for Non-Existent Values:
javascriptconst colors = ['red', 'blue', 'green'];
const hasYellow = colors.includes('yellow');
console.log(hasYellow); // Outputs: false
In this case, the includes() method is used to check if the array colors contain the value 'yellow', and it returns false.
The includes()
method performs a strict equality comparison (===) when searching for the value. This means it checks for both value and data type.
If fromIndex
is negative, it is treated as an offset from the end of the array. If the calculated index is less than 0, the entire array will be searched.
In older JavaScript environments (e.g., older versions of Internet Explorer), the includes() method may not be available. In such cases, you can use a polyfill to add this functionality:
javascriptif (!Array.prototype.includes) {
Array.prototype.includes = function (searchElement, fromIndex) {
// Implementation of the includes method
};
}
The polyfill implementation can vary depending on your specific needs and the JavaScript environment you are working in.
infoThe includes()
method is a handy and simple way to check for the presence of a value in an array. It can be particularly useful for tasks like determining if a certain element exists before performing further operations on the array.