TypeScript: Search an Element in an Array

1. Introduction

Searching is a fundamental concept in computer science. Whether you're looking up a contact on your phone or trying to find a specific email, you're using some form of search algorithm. In this tutorial, we'll explore how to search for an element in an array using TypeScript.

2. Program Overview

We'll implement a basic linear search algorithm. Linear search works by sequentially checking each element of the array until a match is found or the entire array has been searched. This method is straightforward but not the most efficient for large lists.

3. Code Program

function linearSearch(arr: number[], target: number): number {
    // Iterate through each element in the array
    for (let i = 0; i < arr.length; i++) {
        // Check if the current element matches the target
        if (arr[i] === target) {
            return i;  // If found, return the index
    return -1;  // If not found, return -1

// Test the function
const array = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20];
const targetElement = 14;
const index = linearSearch(array, targetElement);
if (index !== -1) {
    console.log(`Element ${targetElement} found at index: ${index}`);
} else {
    console.log(`Element ${targetElement} not found in the array.`);


Element 14 found at index: 6

4. Step By Step Explanation

1. We declare a function linearSearch that takes in an array arr and a target element target.

2. We then use a for loop to iterate through each element in the array.

3. Inside the loop, we compare the current element (arr[i]) with the target. If they match, we've found our element and return the current index i.

4. If we exit the loop without having found the target, it means the target is not present in the array. In this case, we return -1 as a convention to indicate the element was not found.

5. We then test our function with a sample array and a target element. The result is printed to the console.