Mental Model
Look at each item one by one until you find the one you want or reach the end.
Analogy: Imagine looking for a book on a shelf by checking each book from left to right until you find it.
[5] -> [3] -> [7] -> [1] -> [9] -> null ↑
[5] -> [3] -> [7] -> [1] -> [9] -> null ↑
[5↑] -> [3] -> [7] -> [1] -> [9] -> null
[5] -> [3↑] -> [7] -> [1] -> [9] -> null
[5] -> [3] -> [7↑] -> [1] -> [9] -> null
[5] -> [3] -> [7] -> [1↑] -> [9] -> null
[5] -> [3] -> [7] -> [1↑] -> [9] -> null Found value 1 at index 3
class LinearSearch { static search(arr, target) { for (let i = 0; i < arr.length; i++) { if (arr[i] === target) { return i; // found target at index i } } return -1; // target not found } } const array = [5, 3, 7, 1, 9]; const target = 1; const index = LinearSearch.search(array, target); if (index !== -1) { console.log(`Found value ${target} at index ${index}`); } else { console.log(`Value ${target} not found`); }
for (let i = 0; i < arr.length; i++) {if (arr[i] === target) {return i; // found target at index ireturn -1; // target not foundfor (let i = 0; i < arr.length; i++) {
return -1; // target not found
if (arr[i] === target) {