Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

includes
array
typescript
element
communitycreator

How to check if an element exists in an array in TypeScript

Theodore Kelechukwu Onyejiaku

Overview

TypeScript is a superset of JavaScript. With TypeScript, we can add more syntax, catch more errors and do a lot more. TypeScript runs anywhere JavasScript runs.

In this shot, we will check if an array in TypeScript contains an element by using the includes() method. This method returns a boolean value indicating if an element is present in the array.

Syntax

array.includes(element)
Syntax for includes() method

Parameters

element: This is the element we want to check if it is present in the given array.

Return value

If the element is present in the array, then true is returned. Otherwise, false is returned.

Code example

Let's see how this works in the following code:

// 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"]

// check if the arrays contain some elements
console.log(names.includes("Jude"))
console.log(names.includes("Theodore"))
console.log(numbers.includes(3))
console.log(numbers.includes(0.9))
console.log(cars.includes("Bugatti"))
console.log(cars.includes("Toyota"))
Using includes() method on arrays

Explanation

  • Lines 2–5: We create some arrays.
  • Lines 8–13: Using the includes() method, we check to see if some elements are present in the arrays. Then we print the results to the console.

RELATED TAGS

includes
array
typescript
element
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring