Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

typescript
array
includes
communitycreator

What is array.includes in TypeScript?

Theodore Kelechukwu Onyejiaku

Overview

TypeScript is similar to JavaScript in all ramifications. It is the superset of JavaScript. The only difference is that with TypeScript, we can do additional syntax, quick catching, handling of bugs, and so on. TypeScript runs wherever JavaScript runs.

In TypeScript, we can use the includes() method of an array to check if an array includes a certain element or value.

Syntax

array.includes(element)
The syntax for the includes() method in TypeScript

Parameter

element: This is the element we want to check to see if it is a member of the array.

Return value

If the array includes the specified element, then true is returned. Otherwise, it returns false.

Example

Let's look at the code below:

// create arrays in TypeScript
let names: string[] = ["Theodore", "James", "Peter", "Amaka"]
let numbers : Array<number>; 
numbers = [12, 34, 5, 0.9]
let cars : Array<string> = ["Porsche", "Toyota", "Lexus"]
let randomValues : Array<string | number | boolean> = ["one",1, "two", 2, 56, true]

// check if array include some particular elements
console.log(names.includes("Theodore"))
console.log(numbers.includes(10))
console.log(cars.includes("Lexus"))
console.log(randomValues.includes(false))
Checking if an array includes a particular value or element in TypeScript

Explanation

  • Lines 2 to 6: We create some arrays in TypeScript.
  • Lines 9 to 12: We use the includes() method of an array object to check if some elements are members of an array. Then, we print the results to the console.

RELATED TAGS

typescript
array
includes
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring