Linear Search

Scans every element sequentially until the target is found or the array is exhausted; works on unsorted data.

Syntax

linearSearch(arr, target)

Parameters

NameTypeRequiredDescription
arr Array<any> Yes The array to search. May be unsorted and contain any comparable values.
target any Yes The value to find using strict equality (===).

Returns

number — Index of the first matching element, or -1 if not found.

Examples

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

console.log(linearSearch([4, 2, 7, 1, 9, 3], 9));
console.log(linearSearch([4, 2, 7, 1, 9, 3], 5));
Output
4
-1
// Works on unsorted, mixed-type arrays
function linearSearch(arr, target) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === target) return i;
  }
  return -1;
}

const data = ['apple', 'banana', 'cherry'];
console.log(linearSearch(data, 'banana'));
Output
1

Notes

| Case | Time | Space | |---------|------|-------| | Best | O(1) | O(1) | | Average | O(n) | O(1) | | Worst | O(n) | O(1) | Linear search is the only option for unsorted or non-random-access collections (e.g. linked lists). For sorted arrays with random access, binary search reduces this to O(log n). JavaScript's built-in `Array.prototype.indexOf` and `Array.prototype.find` are both linear searches under the hood.

See also