Search in Array in JavaScript

indexOf / includes / find. indexOf missing is -1, not 0. 0 is a real index.

IntermediateArray 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);

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

What's going on

indexOf returns -1 when missing. if (arr.indexOf(x)) is wrong because index 0 is falsy.

includes is the boolean you actually wanted.