Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Search in Array in JavaScript

Search an array in JavaScript with indexOf, includes, find, findIndex, some and binary search. Why missing items give -1. Explanation and output.

IntermediateJavaScript Array ProgramsExample 5 of 6
search-in-array.js
1// Method 1: Using indexOf
2let arr = [10, 20, 30, 40, 50];
3let searchValue = 30;
4
5let index = arr.indexOf(searchValue);
6if (index !== -1) {
7 console.log(`${searchValue} found at index ${index}`);
8} else {
9 console.log(`${searchValue} not found`);
10}
11
12// Method 2: Using includes
13let numbers = [5, 10, 15, 20, 25];
14console.log("\nUsing includes:");
15console.log("15 exists:", numbers.includes(15));
16console.log("35 exists:", numbers.includes(35));
17
18// Method 3: Using find
19let users = [
20 { id: 1, name: "John" },
21 { id: 2, name: "Jane" },
22 { id: 3, name: "Bob" }
23];
24
25let user = users.find(u => u.id === 2);
26console.log("\nUsing find:", user);
27
28// Method 4: Using findIndex
29let index2 = users.findIndex(u => u.name === "Bob");
30console.log("\nFindIndex:", index2);
31
32// Method 5: Using for loop
33function searchArray(arr, value) {
34 for (let i = 0; i < arr.length; i++) {
35 if (arr[i] === value) {
36 return i;
37 }
38 }
39 return -1;
40}
41
42console.log("\nUsing loop:", searchArray([1, 2, 3, 4, 5], 3));
43
44// Method 6: Binary search (sorted array)
45function binarySearch(arr, target) {
46 let left = 0;
47 let right = arr.length - 1;
48
49 while (left <= right) {
50 let mid = Math.floor((left + right) / 2);
51
52 if (arr[mid] === target) {
53 return mid;
54 } else if (arr[mid] < target) {
55 left = mid + 1;
56 } else {
57 right = mid - 1;
58 }
59 }
60 return -1;
61}
62
63let sorted = [1, 3, 5, 7, 9, 11, 13];
64console.log("\nBinary search:", binarySearch(sorted, 7));
65
66// Method 7: Using some (check existence)
67let hasEven = [1, 3, 5, 7, 8].some(num => num % 2 === 0);
68console.log("\nHas even number:", hasEven);

Sample 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

In this one

  • How indexOf reports a missing value
  • Why if (arr.indexOf(x)) is a bug
  • When to use includes, find and findIndex
  • How binary search halves a sorted list

How it works

  1. 1

    indexOf(30) returns 2.

  2. 2

    includes checks 15 (true) and 35 (false).

  3. 3

    find returns the user with id 2.

  4. 4

    findIndex finds Bob at index 2.

  5. 5

    binarySearch finds 7 at index 3.

  6. 6

    some finds the even number 8.

Edge cases

Item at index 0

if ([5, 6].indexOf(5)) is false.

indexOf returned 0, which is falsy. Compare with !== -1 or use includes.

Searching for NaN

[NaN].indexOf(NaN) is -1 but [NaN].includes(NaN) is true.

indexOf uses ===, and NaN is never === NaN. includes handles it.

Binary search on unsorted data

binarySearch([5, 1, 9], 1) can return -1.

Sort the array first. Binary search assumes order.

What's going on

This program looks for a value in an array in seven ways. Searching is everywhere: finding a roll number in an attendance list, or a product in a cart.

indexOf returns the position of the first match. Positions start at 0. If the value is missing, it returns -1. Not 0. 0 is a real index, the first item.

That causes a classic bug. if (arr.indexOf(x)) looks fine, but when x is the first item, indexOf returns 0. 0 is falsy, which means it counts as false in an if. So your code says "not found" for the first item. Always compare with !== -1, as Method 1 does.

includes returns true or false. If you only need "is it there?", this is the boolean you actually wanted.

find and findIndex work on arrays of objects. You pass a callback, a function that tests each item. find returns the first matching object, or undefined. findIndex returns its position, or -1.

Method 5 is the manual for loop, so you can see what indexOf does inside.

Method 6 is binary search. It only works on a sorted array. It looks at the middle item. If the target is bigger, it drops the left half. If smaller, it drops the right half. Each step halves the search, so 1,000 items need about 10 checks.

some returns true if at least one item passes a test, such as "is any number even?".

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does [4, 5].indexOf(9) return?

Pick an answer to check it.

Question 2

Which method returns true or false?

Pick an answer to check it.

Questions people ask

What does find return if nothing matches?

undefined.

Is binary search always better?

Only on sorted data with many items. For small arrays indexOf is fine.

Does includes work on objects?

Only if you pass the exact same object reference. Use find for matching by property.