JavaScript Array includes() Tutorial

In this section, we will learn what the includes() method is and how to use it in JavaScript.

JavaScript Arrays includes() Method

The `includes()` method can be used to determine whether an Array object has a specific element in it.

For example, let’s say there’s an array named “arr” and now we want to know if it has the value “John” as one of its element! This is where we can use the includes() method.

Array includes() Syntax:

array.includes(element, start)

Array includes() Method Parameters:

The method takes two arguments:

  • The first argument is the element that we want to see if it’s in the target Array object.
  • The second argument specifies the location from which the search should begin.

Note: this argument is optional and if ignored, the search will start from the index 0 of the target array.

Array includes() Method Return Value:

The return value of this method is a Boolean.

If the value is `true` that means the element exists in the target array.

If the value was `false` that means there’s no such element in the target array.

Example: using Array includes() method in JavaScript

const obj1 = {
   name: "John", 
   age: 1000
}
const obj2 = {
   name: "Omid",
   age: 29
}
const obj3 = {
   name : "Jack", 
   age :52
}
const arr = [obj1,obj2,obj3];
console.log (arr.includes(obj2));

Output:

true

Example: JavaScript check value in array

const arr = ["Apple","Google","Microsoft", "Apple","Tesla"];

console.log(arr.includes("Microsoft"));

Output:

true

Leave a Reply