Introduction to includes() in JavaScript
Explore JavaScript's array-friendly includes() method. Includes(), one of JavaScript's renowned array methods, is useful. The function returns true or false if an array element is hanging. Easy, right?
Fun fact: includes() compares items using the sameValueZero approach and is case-sensitive. Thus, it can detect NaN values that other comparison algorithms overlook. Includes() doesn't tamper with your original array, which is wonderful. Check your array's contents without damaging it. A tremendous win!
Includes() is useful for everything from verifying data to building complicated algorithms.
Syntax and Parameters of includes()
JavaScript includes() is easy! A few parameters are needed:
- searchElement: The thing you're looking for in the array.
- fromIndex (optional): Where you want to start the search in the array.
Want to see how it works in action? Check this out:
let array = [1, 2, 3, 4, 5];
console.log(array.includes(2)); // Returns true
console.log(array.includes(6)); // Returns false
We play detective to find 2 or 6 in our array in this sample. With 2 present, the first log returns a thumbs up (true), while with 6 absent, the second returns a thumbs down (false). You can also toss in the fromIndex parameter if you want to start the search from a particular spot. And hey, if you throw in a negative number, it'll count backwards from the end of the array!
Here's how that looks:
let array = [1, 2, 3, 4, 5];
console.log(array.includes(2, 3)); // Returns false
console.log(array.includes(2, -4)); // Returns true
We search index 3 for 2 in that first log, but it's false. The second example finds 2 by starting our search a few steps back in the array (-4) (true).
Understanding Return Values of includes()
So, what's the deal with the return values of the includes() method? It's all about the booleans here—you're getting either a true or a false, no surprises. If your array has the element you’re looking for, it’ll give you a true. If not, it's a false.
Let’s break it down with an easy example:
let array = ['apple', 'banana', 'cherry'];
console.log(array.includes('banana')); // Returns true
console.log(array.includes('grape')); // Returns false
See what's happening? The first check comes back true because we’ve got 'banana' in the mix. But when we asked about 'grape', it’s a no-go with a false since grapes didn’t make the cut. Oh, and a quick heads-up: includes() is picky about case. So, 'banana' and 'Banana' are totally different in its eyes.
Check this out:
let array = ['apple', 'banana', 'cherry'];
console.log(array.includes('Banana')); // Returns false
For 'Banana', it says false. It must match everything, even capitals. Another clever includes() trick? It can detect NaN values, unlike other approaches.
This illustrates that:
let array = [1, 2, NaN, 4, 5];
console.log(array.includes(NaN)); // Returns true
NaN is chilling in the array, therefore it returns true. This minor feature makes includes() a favorite for situations where other techniques fail.
Practical Examples of includes() in Action
Includes() is a programming Swiss Army knife—versatile and helpful. Let's test it on actual code.
- User Permissions: Select a role from a list to determine club membership.
let userRoles = ['admin', 'editor', 'subscriber'];
let user = 'editor';
if (userRoles.includes(user)) {
console.log('Access granted.');
} else {
console.log('Access denied.');
}
As 'editor' is in userRoles, the console will indicate 'Access granted.'
- Form Validation: Want a selection for supported nations? Approval depends on includes():
let supportedCountries = ['USA', 'Canada', 'UK', 'Australia'];
let userCountry = 'France';
if (supportedCountries.includes(userCountry)) {
console.log('Country supported.');
} else {
console.log('Country not supported.');
}
'France' displays 'Country not supported.'
- Filtering Search Results: Site search? Includes() filters 'apple' titles and descriptions:
let searchResults = [
{title: 'Apple Pie Recipe', description: 'A delicious apple pie recipe.'},
{title: 'Banana Bread Recipe', description: 'A tasty banana bread recipe.'},
{title: 'Cherry Pie Recipe', description: 'A sweet cherry pie recipe.'}
];
let searchTerm = 'apple';
let filteredResults = searchResults.filter(item =>
item.title.includes(searchTerm) || item.description.includes(searchTerm)
);
console.log(filteredResults);
Filtered title and description include 'apple'. Only the first result shown.
Comparing includes() with indexOf()
IndexOf() checked if an array had a member before includes(). However, they differ greatly. indexOf() returns the first entry in the array or -1 if none exists. includes() simply returns true or false to indicate element presence.
How they differ:
let array = [1, 2, 3, 4, 5];
console.log(array.indexOf(3)); // Returns 2
console.log(array.includes(3)); // Returns true
IndexOf() gives 2 since 3 is in the array. Includes() returns true since 3 is there. Unlike indexOf(), includes() easily captures NaN.
let array = [1, 2, NaN, 4, 5];
console.log(array.indexOf(NaN)); // Returns -1
console.log(array.includes(NaN)); // Returns true
Since there are no NaNs in the array, IndexOf() returns -1. Includes() returns true. IndexOf() helps, but includes() checks array members, including NaN, more precisely and easily.
Performance Considerations of includes()
When we're talking performance, the includes() method is usually a speedster for most scenarios. But here's the scoop: includes() has a time complexity of O(n). That means the bigger the array, the longer it might take to do its thing, since it may need to check each element one by one.
For our usual smaller or medium-sized arrays, this isn't really a biggie. You'll likely not notice any slowdowns. But once you get into giant array territory, you might start feeling the lag. If you're working with those huge arrays and starting to worry about speed, you might want to think about using other data structures, like Sets or Maps, which are quicker on the draw when it comes to looking up stuff.
Check out this example to see what I mean:
let largeArray = Array(10000000).fill('test');
let largeSet = new Set(largeArray);
console.time('Array includes');
largeArray.includes('test'); // Takes longer
console.timeEnd('Array includes');
console.time('Set has');
largeSet.has('test'); // Faster
console.timeEnd('Set has');
We compare how long it takes to find anything in a large array vs a Set. Set's has() function is faster than array's includes(). Don't worry—most items you make have little speed difference. Includes() works great until you're using big arrays.
Common Errors and Troubleshooting with includes()
Despite its simplicity, the includes() function often causes issues. Learn how to avoid typical mix-ups.
- Calling includes() on non-arrays: includes() is part of the Array prototype and only works on arrays. Using it on a non-array will throw a TypeError.
let notAnArray = 'This is a string';
console.log(notAnArray.includes('is')); // TypeError: notAnArray.includes is not a function
Fixing this is simple! Just make sure you’re only calling includes() on arrays.
- Case Sensitivity: The includes() method is picky about case, so 'apple' and 'Apple' are seen as different. If you're not careful, this can throw off your results.
let array = ['apple', 'banana', 'cherry'];
console.log(array.includes('Apple')); // Returns false
Prevent surprises by converting everything to the same case, like all lowercase, before calling includes().
- Working with NaN: Unlike some methods, includes() detects NaN easily. But if you're not expecting it, this can catch you off guard.
let array = [1, 2, NaN, 4, 5];
console.log(array.includes(NaN)); // Returns true
Arrays with NaN values require this.
- Non-integer fromIndex Values: If fromIndex isn't a full number, includes() starts from 0.
let array = [1, 2, 3, 4, 5];
console.log(array.includes(1, 1.5)); // Returns true
Includes() checks from the start and ignores the decimal. Just make sure fromIndex is an integer to avoid issues.
includes() in ES6 and Browser Compatibility
In ES6, the includes() function debuted. Modern browsers like Chrome, Firefox, Safari, and Edge support it, while older browsers, especially Internet Explorer, don't. If your project has to serve these old-timers, you may require a workaround.
Enter the polyfill! It’s like giving your browser a crash course in modern JavaScript. A polyfill is a chunk of code that steps in to provide the functionality you’d expect the browser to handle on its own.
Check out this simple polyfill for includes():
if (!Array.prototype.includes) {
Array.prototype.includes = function(searchElement, fromIndex) {
'use strict';
if (this == null) {
throw new TypeError('Array.prototype.includes called on null or undefined');
}
var o = Object(this);
var len = o.length >>> 0;
if (len === 0) {
return false;
}
var n = fromIndex | 0;
var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
function sameValueZero(x, y) {
return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
}
while (k < len) {
if (sameValueZero(o[k], searchElement)) {
return true;
}
k++;
}
return false;
};
}
If lacking, this clever polyfill adds the includes() function to the Array prototype. This lets you utilize includes() in settings that don't follow JavaScript trends.
Advanced Use Cases of includes()
The includes() function has complex techniques as well as simple ones. Its versatility and simplicity make it ideal for difficult jobs.
Here are some cool uses:
- Searching in Nested Arrays: Got nested arrays? You may use includes() and some() to find a specific element in those subarrays.
let nestedArray = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let searchElement = 5;
let found = nestedArray.some(subArray => subArray.includes(searchElement));
console.log(found); // Returns true
Here, some() checks out each sub-array to see if any of them have our search item. When it matches, it returns true.
- Multiple-Element Check: Want to check if an array contains several elements? Combine includes() with some() and a list of intriguing items.
let array = ['apple', 'banana', 'cherry'];
let elementsToCheck = ['banana', 'grape', 'kiwi'];
let found = elementsToCheck.some(element => array.includes(element));
console.log(found); // Returns true
In this setup, some() peeks at each item in your list of elementsToCheck to see if they're in the main array. Find at least one, and it returns true.
- Excluding Certain Values: Need to weed out some specific values from an array? Use includes() with filter() to craft a new array minus the ones you want gone.
let array = [1, 2, 3, 4, 5];
let valuesToExclude = [2, 4];
let filteredArray = array.filter(element => !valuesToExclude.includes(element));
console.log(filteredArray); // Returns [1, 3, 5]
A new array containing just the entries not in valuesToExclude is created by filter(). includes() searches for matches, and! flips the result to exclude them.