0
0
JavascriptHow-ToBeginner · 3 min read

How to Check if Array Includes Element in JavaScript

Use the includes() method on an array to check if it contains a specific element. It returns true if the element is found, otherwise false. For example, array.includes(element).
📐

Syntax

The includes() method is called on an array and takes one required argument: the element to search for. It returns a boolean indicating if the element exists in the array.

  • array: The array you want to check.
  • element: The value you want to find in the array.
javascript
array.includes(element)
💻

Example

This example shows how to check if the number 3 is in the array. It prints true if found, otherwise false.

javascript
const numbers = [1, 2, 3, 4, 5];
const hasThree = numbers.includes(3);
console.log(hasThree);
Output
true
⚠️

Common Pitfalls

One common mistake is using includes() with objects or arrays inside arrays, which checks by reference, not by value. Also, includes() is case-sensitive for strings.

Wrong example: searching for an object inside an array of objects will fail unless it is the exact same object.

javascript
const arr = [{id: 1}, {id: 2}];
console.log(arr.includes({id: 1})); // false because different object reference

// Correct way: check by property
const found = arr.some(item => item.id === 1);
console.log(found); // true
Output
false true
📊

Quick Reference

MethodDescriptionReturns
includes(element)Checks if element exists in arraytrue or false
some(callback)Checks if any element passes testtrue or false
indexOf(element)Returns index or -1 if not foundnumber

Key Takeaways

Use includes() to check if an array contains a specific element easily.
includes() returns true or false based on presence of the element.
For objects or complex types, use some() with a test function instead.
includes() is case-sensitive for strings and checks by strict equality.
Remember includes() works on arrays and strings in JavaScript.