Search in Array

Program to search for an element in an array

IntermediateTopic: Array Programs
Back

JavaScript Search in Array Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Method 1: Using indexOf
let arr = [10, 20, 30, 40, 50];
let searchValue = 30;

let index = arr.indexOf(searchValue);
if (index !== -1) {
    console.log(`${searchValue} found at index ${index}`);
} else {
    console.log(`${searchValue} not found`);
}

// Method 2: Using includes
let numbers = [5, 10, 15, 20, 25];
console.log("\nUsing includes:");
console.log("15 exists:", numbers.includes(15));
console.log("35 exists:", numbers.includes(35));

// Method 3: Using find
let users = [
    { id: 1, name: "John" },
    { id: 2, name: "Jane" },
    { id: 3, name: "Bob" }
];

let user = users.find(u => u.id === 2);
console.log("\nUsing find:", user);

// Method 4: Using findIndex
let index2 = users.findIndex(u => u.name === "Bob");
console.log("\nFindIndex:", index2);

// Method 5: Using for loop
function searchArray(arr, value) {
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === value) {
            return i;
        }
    }
    return -1;
}

console.log("\nUsing loop:", searchArray([1, 2, 3, 4, 5], 3));

// Method 6: Binary search (sorted array)
function binarySearch(arr, target) {
    let left = 0;
    let right = arr.length - 1;
    
    while (left <= right) {
        let mid = Math.floor((left + right) / 2);
        
        if (arr[mid] === target) {
            return mid;
        } else if (arr[mid] < target) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    return -1;
}

let sorted = [1, 3, 5, 7, 9, 11, 13];
console.log("\nBinary search:", binarySearch(sorted, 7));

// Method 7: Using some (check existence)
let hasEven = [1, 3, 5, 7, 8].some(num => num % 2 === 0);
console.log("\nHas even number:", hasEven);
Output
30 found at index 2

Using includes:
15 exists: true
35 exists: false

Using find: { id: 2, name: 'Jane' }

FindIndex: 2

Using loop: 2

Binary search: 3

Has even number: true

Understanding Search in Array

This program demonstrates different methods to search for elements in arrays.

Method 1: indexOf()

Finds first occurrence:

let index = arr.indexOf(value);

Returns:

Index if found
-1 if not found

Method 2: includes()

Checks existence:

arr.includes(value);

Returns:

Boolean (true/false)

Method 3: find()

Finds first matching element:

arr.find(item => condition);

Use case:

Objects, complex conditions

Method 4: findIndex()

Finds index of first match:

arr.findIndex(item => condition);

Returns:

Index or -1

Method 5: For Loop

Manual search:

for (let i = 0; i < arr.length; i++) {
    if (arr[i] === value) return i;
}
return -1;

Method 6: Binary Search

For sorted arrays only:

// Divide and conquer
// O(log n) time complexity

How it works:

1.Compare with middle element
2.If equal, found
3.If target < middle, search left half
4.If target > middle, search right half
5.Repeat until found or exhausted

Time Complexity:

Linear search: O(n)
Binary search: O(log n) - Much faster!

Method 7: some()

Check if any element matches:

arr.some(item => condition);

Returns:

Boolean

When to Use:

-

indexOf/includes

: Simple value search

-

find/findIndex

: Objects, conditions

-

Binary search

: Sorted arrays, large data

-

some

: Existence check

-

Loop

: Custom logic, learning

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Practical Learning Notes for Search in Array

This JavaScript program is part of the "Array Programs" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents