JavaScript : How to checks whether an array includes a certain element

Java Script @

JavaScript arrays offer a wide array of methods for efficient manipulation and traversal. Among these, the includes() method is particularly useful for checking the presence of an element within an array. In this article, we’ll delve into the intricacies of includes(), its syntax, functionality, and practical applications with detailed examples.

Understanding includes()

The includes() method in JavaScript checks whether an array includes a certain element, returning true or false accordingly. It provides a straightforward way to perform element detection within arrays without the need for manual iteration.


The syntax for includes() is simple:

array.includes(element, start);

Here, array represents the array to search, element is the element to search for, and start (optional) is the position in the array from which to start the search.


Let’s explore various scenarios to understand the versatility of includes():

Example 1: Basic Usage

const fruits = ['apple', 'banana', 'orange', 'grape'];
// Output: true
// Output: false

Example 2: Using start Parameter

const nums = [1, 2, 3, 4, 5];
console.log(nums.includes(3, 2));
// Output: true (search starts from index 2)
console.log(nums.includes(3, 3));
// Output: false (search starts from index 3)

Example 3: Handling NaN

const arr = [1, 2, NaN, 4];
// Output: true

The includes() method in JavaScript simplifies array searching and element detection, providing a concise and efficient solution. Whether it’s checking for the presence of a specific value or verifying the inclusion of NaN, includes() streamlines the process with its intuitive syntax and functionality.

Author: user