Linear search in JavaScript
Beginner · 3 min read
Linear search is the simplest way to find something in a list: start at the beginning and look at each item in turn until you find it. It is what you do when you scan a bus park for one plate number, and it is what JavaScript's own indexOf does under the hood.
In this tutorial you will write linearSearch yourself, return the right thing when the item is missing, and then make a more flexible version that searches by a rule instead of an exact value. You need to know arrays and for loops. Everything else is explained as we go.
What a search should return
A search could answer just "yes" or "no". Returning the item's index, its position in the list, is more useful. It tells you the item is there and where it is, so you can read it, change it or remove it.
Indexes start at 0, so the first item is at index 0. That means 0 can't be used for "not found". JavaScript's built-in methods use -1 for that, so we will too:
const plates = ['LAG-441-XA', 'ABJ-772-KM', 'ENU-318-PH'];
console.log(plates.indexOf('ENU-318-PH')); // 2
console.log(plates.indexOf('KAN-905-BD')); // -1
Why "linear"
In the worst case, the item is last or missing, and you look at every item once. Twice as many items means about twice the work. That straight-line growth is where the name comes from. People write it as O(n), "order n", where n is the number of items.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
1 Linear search
easyWalk a list from the start and return the position of the first match, or a value meaning "not there".
Stuck? Three hints, smallest first
- 1. Return the index, not
true. An index is strictly more useful and still tells you it was found. - 2. Return
-1for not found, matchingindexOf, so callers already know the convention. - 3. This is the only search that works on unsorted data, which is its whole point.
Step 1: look at every item
A for loop visits each index from 0 up to the last one. Inside, compare the item with the target using ===:
const plates = ['LAG-441-XA', 'ABJ-772-KM', 'ENU-318-PH'];
for (let i = 0; i < plates.length; i++) {
console.log(i, plates[i] === 'ENU-318-PH');
}
// 0 false
// 1 false
// 2 true
Step 2: stop at the first match
Inside a function, return ends the function straight away. So the moment we find a match, we return its index and the loop stops:
function linearSearch(values, target) {
for (let i = 0; i < values.length; i++) {
if (values[i] === target) return i;
}
return -1;
}
const plates = ['LAG-441-XA', 'ABJ-772-KM', 'ENU-318-PH', 'ABJ-772-KM'];
console.log(linearSearch(plates, 'ENU-318-PH')); // 2
console.log(linearSearch(plates, 'KAN-905-BD')); // -1
console.log(linearSearch(plates, 'ABJ-772-KM')); // 1
console.log(linearSearch([], 'x')); // -1
The return -1 sits after the loop. It only runs when the loop has finished without finding anything. 'ABJ-772-KM' appears twice, and we get 1, the first one, because the search stops there.
Step 3: the wrong turn
A common mistake is to put the "not found" answer inside the loop:
function broken(values, target) {
for (let i = 0; i < values.length; i++) {
if (values[i] === target) return i;
else return -1;
}
return -1;
}
console.log(broken(['a', 'b', 'c'], 'c')); // -1, but 'c' is at index 2
The else returns on the very first item that doesn't match, so the loop never gets past index 0. You can only say "not found" after checking everything.
Step 4: search by a rule
Sometimes you don't know the exact value. You want "the first plate starting with ENU". Pass a function, often called a predicate, that answers true or false for each item:
function searchBy(values, matches) {
for (let i = 0; i < values.length; i++) if (matches(values[i], i)) return i;
return -1;
}
const plates = ['LAG-441-XA', 'ABJ-772-KM', 'ENU-318-PH'];
console.log(searchBy(plates, (p) => p.startsWith('ENU'))); // 2
console.log(plates.findIndex((p) => p.startsWith('ENU'))); // 2
That is exactly what the built-in findIndex does, and the two agree.
The full solution
The panel has both functions and runs them on a list of plate numbers, including a missing one and a duplicate. Press Run. The checks confirm the results match indexOf and findIndex, and that it works on unsorted numbers too.
function linearSearch(values, target) {
for (let i = 0; i < values.length; i++) {
if (values[i] === target) return i;
}
return -1; // same convention as indexOf
}
// A version taking a predicate, which is what findIndex does.
function searchBy(values, matches) {
for (let i = 0; i < values.length; i++) if (matches(values[i], i)) return i;
return -1;
}
const plates = ['LAG-441-XA', 'ABJ-772-KM', 'ENU-318-PH', 'ABJ-772-KM'];
console.log('found at :', linearSearch(plates, 'ENU-318-PH'));
console.log('not present :', linearSearch(plates, 'KAN-905-BD'));
console.log('first of two:', linearSearch(plates, 'ABJ-772-KM'));
console.log('by predicate:', searchBy(plates, (p) => p.startsWith('ENU')));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a match returns its index', linearSearch(plates, 'ENU-318-PH'), 2);
test('the first index wins on duplicates', linearSearch(plates, 'ABJ-772-KM'), 1);
test('absent gives -1', linearSearch(plates, 'KAN-905-BD'), -1);
test('an empty list gives -1', linearSearch([], 'x'), -1);
test('it agrees with indexOf', linearSearch(plates, 'ABJ-772-KM'), plates.indexOf('ABJ-772-KM'));
test('the predicate version finds by rule', searchBy(plates, (p) => p.startsWith('ENU')), 2);
test('and agrees with findIndex', searchBy(plates, (p) => p.startsWith('ENU')), plates.findIndex((p) => p.startsWith('ENU')));
test('it works on unsorted data', linearSearch([5, 1, 9, 3], 9), 2);
Linear search is O(n) and is the right answer more often than people expect: it needs no sorting, no preparation, and for a few hundred items the difference against a binary search is unmeasurable. Returning -1 rather than null matches indexOf and findIndex, so callers do not have to learn a new convention.
Common mistakes
- Returning -1 inside the loop. The search gives up after the first item. Put
return -1after the loop. - Using 0 or
falsefor "not found". 0 is a real index. Stick with -1, the same asindexOf. - Writing
if (linearSearch(...))to check if it was found. Index 0 is falsy, so a match at the start looks like a miss. Compare with!== -1.
Try it yourself
- Write
lastIndex(values, target)that loops from the end and returns the last match. - Write
countMatches(values, target)that doesn't stop early and counts every match. - Change
linearSearchto return the number of comparisons it made as well, and try it on a missing item.