Open In App

TypeScript Array includes() Method

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

TypeScript includes() method allows you to determine if a specific element is present, within an array.

can also determine if a particular element exists or not at a particular index position.

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

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads