Backbencher.dev

Linear Search Using JavaScript

Last updated on 8 Dec, 2022

Here is a function that implements linear search using JavaScript:

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

Lines 2 to 6: Loop through the input array. If we find the item we are searching for, return its index.

Line 7: -1 is returned if the item is not found.

Here is how we can run it:

const arr = [2, 4, 6, 8, 10];
const item = 4;
const index = linearSearch(arr, item);
console.log(index); // 1

Big O

Big O of linear search is O(n).

--- ○ ---
Joby Joseph
Web Architect