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 indexOf2let arr = [10, 20, 30, 40, 50];3let searchValue = 30;45let index = arr.indexOf(searchValue);6if (index !== -1) {7 console.log(`${searchValue} found at index ${index}`);8} else {9 console.log(`${searchValue} not found`);10}1112// Method 2: Using includes13let numbers = [5, 10, 15, 20, 25];14console.log("\nUsing includes:");15console.log("15 exists:", numbers.includes(15));16console.log("35 exists:", numbers.includes(35));1718// Method 3: Using find19let users = [20 { id: 1, name: "John" },21 { id: 2, name: "Jane" },22 { id: 3, name: "Bob" }23];2425let user = users.find(u => u.id === 2);26console.log("\nUsing find:", user);2728// Method 4: Using findIndex29let index2 = users.findIndex(u => u.name === "Bob");30console.log("\nFindIndex:", index2);3132// Method 5: Using for loop33function 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}4142console.log("\nUsing loop:", searchArray([1, 2, 3, 4, 5], 3));4344// Method 6: Binary search (sorted array)45function binarySearch(arr, target) {46 let left = 0;47 let right = arr.length - 1;4849 while (left <= right) {50 let mid = Math.floor((left + right) / 2);5152 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}6263let sorted = [1, 3, 5, 7, 9, 11, 13];64console.log("\nBinary search:", binarySearch(sorted, 7));6566// 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: trueWhat'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.