.includes() method returns
true if a given value is included in an array. Otherwise, it returns
The following parameters are used:
- A case-sensitive and type-sensitive
valuethat is checked for inclusion in the
- An optional
index, defaulted to 0, that tells
.includes()where to begin the check.
Here are some edge-cases to consider when using
- It will not work if the provided
indexis greater than the length of the array. Instead,
falsewill be returned.
- If the
indexis less than or equal to 0, the entire array will be searched.
- By itself, this method isn’t suitable for nested array and should be used with the
- For objects,
truefor references of the same object (even checking against an object with the same property-value pairs returns
.includes() method can be used in a few ways. First, it can be used directly with an array:
console.log([1, 2, 3].includes(3));// Output: true
It can also be used with an array assigned to a variable:
const myArray = [1, '2', 3];console.log(myArray.includes(2));// Output: false
The output above is
.includes() is type-sensitive. A number-type value 2 was checked for when
myArray has no such value. Instead, it has a string literal that reads as ‘2’.
The example below uses
.includes() on an array,
myArray, to check for an object reference, an object literal, and a number.