.includes()
Published Mar 21, 2022
Contribute to Docs
The .includes()
method returns true
if a given value is included in an array. Otherwise, it returns false
.
Syntax
array.includes(value, index=0);
The following parameters are used:
- A case-sensitive and type-sensitive
value
that is checked for inclusion in thearray
. - An optional
index
, defaulted to 0, that tells.includes()
where to begin the check.
Here are some edge-cases to consider when using .includes()
:
- It will not work if the provided
index
is greater than the length of the array. Instead,false
will be returned. - If the
index
is 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
.flat()
and/or.find()
methods. - For objects,
.includes()
only returnstrue
for references of the same object (even checking against an object with the same property-value pairs returnsfalse
).
Example
The .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 false
because .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’.
Codebyte Example
The example below uses .includes()
on an array, myArray
, to check for an object reference, an object literal, and a number.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn JavaScript on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner Friendly15 hours