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