Open In App

TypeScript Array includes() Method

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:

Return Value:

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




// 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.




// 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
Article Tags :