.includes()
The .includes()
method is a built-in function in JavaScript that allows you to check if an array contains a specific element. It returns a boolean value (true
or false
) based on whether the element is found in the array or not.
Here’s the basic syntax of the .includes()
method:
const isIncluded = array.includes(element);
element
: The element you want to check for in the array.isIncluded
: A boolean indicating whether the element is found in the array (true
) or not (false
).
Here’s an example to illustrate how .includes()
works:
const fruits = ['apple', 'banana', 'orange'];
const hasBanana = fruits.includes('banana');
const hasGrapes = fruits.includes('grapes');
console.log(hasBanana); // Output: true
console.log(hasGrapes); // Output: false
In this example, the .includes()
method is used to check if the array fruits
contains the strings 'banana'
and 'grapes'
. The result is true
for 'banana'
and false
for 'grapes'
.
Keep in mind the following points when using .includes()
:
- Returns Boolean: The
.includes()
method returnstrue
if the specified element is found in the array, andfalse
otherwise. - Case Sensitivity:
.includes()
performs a case-sensitive search. So'Apple'
and'apple'
would be considered different elements. - NaN Comparison:
.includes()
can be used to check for the presence ofNaN
in an array. - IndexOf vs. Includes:
.includes()
is a more concise and straightforward way to check for the existence of an element in an array compared to using.indexOf()
, which returns the index of the element if found, or-1
if not found. - Use Cases:
.includes()
is handy when you want to quickly determine whether a particular element exists in an array without needing its index. - Comparison with Primitives: When comparing non-primitive values (like objects or arrays),
.includes()
uses strict equality (===
) to check for equality.
In summary, the .includes()
method is a convenient way to check if an array contains a specific element. It’s useful for quickly determining whether a value is present in an array without the need for complex logic or iterations.