Approach 3 Using a for loop

Using a for loop, iterate through the array elements, comparing each element to the target. If a match is found, return true; otherwise, return false after iterating through all elements.

Example: In this example The searchElement function iterates through an array to find a target element and returns its index if found, otherwise returns -1.

JavaScript
function searchElement(arr, target) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === target) {
            return i; // Return index if found
        }
    }
    return -1; // Return -1 if not found
}

const array = [10, 20, 30, 40, 50, 60];
const targetElement = 30;
const result = searchElement(array, targetElement);
console.log(`The index of ${targetElement} is: ${result}`);

output:

The index of 30 is: 2

JavaScript Program to Search an Element in an Array

A JavaScript program searches an element in an array by iterating through each item and comparing it with the target value. If found, it returns the index; otherwise, it returns -1, indicating absence.

Following are the ways to search for an element in an array:

Table of Content

  • Using Recursive Approach
  • Using Array.reduce() method
  • Using a for loop:
  • Using Array.indexOf():
  • Using includes

Similar Reads

Approach 1: Using Recursive Approach

The recursive approach in JavaScript for binary search involves dividing the array recursively until finding the target element or exhausting the search space, returning the element’s index or -1 accordingly....

Approach 2: Using Array.reduce() method

The binary search is implemented with Array.reduce() iterates through the array, accumulating results. It returns the index of the target element or -1 if not found, with linear time complexity....

Approach 3: Using a for loop:

Using a for loop, iterate through the array elements, comparing each element to the target. If a match is found, return true; otherwise, return false after iterating through all elements....

Approach 4: Using Array.indexOf():

To search an element in an array using `Array.indexOf()`, provide the element to search for as an argument. It returns the index of the first occurrence of the element, or -1 if not found....

Approach 5: Using includes

Using the includes method, you can check if an array contains a specific element. This method returns true if the element is found and false otherwise. It provides a simple and readable way to verify the presence of an element within an array....