Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Linear search

Linear search checks array elements in order until it finds a match or reaches the end. It needs no sorting; the demonstrated function returns the index of the first match or -1.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

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

Linear search (linear search) is an algorithm, not a JavaScript keyword. It checks elements sequentially, starting at index 0, and stops at the first match. The array does not need to be sorted. linearSearch(array, target) returns the matching element's index or -1, including for an empty array.

The example uses ===: it does not convert types, so the number 8 does not match the string "8". NaN does not match even NaN, and objects match only when they are the same object. The function does not modify the array. The example assumes an ordinary array without holes that remains unchanged during the search.

For n elements, the worst case requires n comparisons: time is O(n) and auxiliary space is O(1), assuming constant-cost reads and comparisons. An immediate match takes O(1) time. Test the result with index !== -1, not if (index): the valid index 0 is falsy, while -1 is truthy.

The built-in array.indexOf(target) also returns the first index using strict comparison, but skips missing indexed properties; the demonstrated loop reads them, usually obtaining undefined. The algorithm has no ECMAScript edition of its own; the example uses syntax available in ES3 and needs neither Web APIs nor modern array methods.

Examples

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

var values = [8, 3, 8, 5];
console.log(linearSearch(values, 8));
console.log(linearSearch(values, 5));
console.log(linearSearch(values, 9));
console.log(linearSearch([], 8));

Result

0
3
-1
-1

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources