JavaScript algorithm: linear search

Linear search (also called sequential search or simple search) is the most basic search algorithm. Given a data structure, such as an array, we search for an item by looking at all the elements until we find it.

Its implementation is very simple:

const linearSearch = (list, item) => {
  for (const [i, element] of list.entries()) {
    if (element === item) {
      return i
    }
  }
}

This will return the index of the item we are looking for. example:

linearSearch(['a', 'b', 'c', 'd'], 'd') //3 (index start at 0)

If we look for "a", the algorithm will only look for the first element and return, so it is very fast.

However, if we are looking for the last element, the algorithm needs to traverse all the arrays. In order to calculate the Big O value, we always consider the worst case.

and soAlgorithm complexityYesO(n).

Download mine for freeJavaScript beginner's manual


More js tutorials: