TypeScript Array includes() Method

Last Updated : 3 Sep, 2024

The TypeScript Array.includes() method checks if an array contains a specified element, returning true if found and false otherwise. It performs a strict equality comparison (===), works with all data types, and correctly identifies NaN in arrays.

Syntax

array.includes(searchElement[, fromIndex])

Parameters:

  • searchElement: The value to search for within the array.
  • fromIndex (optional): The starting index at which to begin searching.

Return Value:

  • It will return true if the array contains the search element, and false otherwise.

Example 1: In this example, we will check whether a given array contains a particular element.

JavaScript
// Here we are defing an array
const fruits: string[] = 
	["apple", "banana", "orange"];

// Here we will check if 
// the array contains "apple"
const hasApple: boolean = 
	fruits.includes("apple");

// Here we will print the result on console
console.log(hasApple);

Output:

true

Example 2: In this example, we will check whether a number exists or not at a given particular index position from starting.

JavaScript
// Here we are defing an array of numbers
const numbers: number[] = [1, 2, 3, 1];

// Declare the starting index 
// with type annotation
const startIndex: number = 2;

// Here we will check the number 
// 1 exists starting from index 2
const foundSecond1: boolean = 
    numbers.slice(startIndex).includes(1);

// Print the result on the console window
console.log(foundSecond1);

Output:

true
Comment
Article Tags:

Explore