0
0
DSA Javascriptprogramming~3 mins

Why Linear Search Algorithm in DSA Javascript?

Choose your learning style9 modes available
The Big Idea

What if you could find anything in a messy list without missing a single item?

The Scenario

Imagine you have a messy drawer full of different colored socks, and you need to find a red sock. You start picking up each sock one by one, checking its color until you find the red one.

The Problem

Searching this way can take a long time if the drawer is big. You might miss the sock or get tired, making mistakes. It's slow and frustrating to check every single sock manually.

The Solution

The linear search algorithm does exactly what you do but faster and without mistakes. It checks each item in a list one by one until it finds the target, making the search simple and reliable.

Before vs After
Before
const socks = ['blue', 'green', 'yellow', 'red', 'black'];
let found = false;
for (let i = 0; i < socks.length; i++) {
  if (socks[i] === 'red') {
    found = true;
    break;
  }
}
After
function linearSearch(items, target) {
  for (let index = 0; index < items.length; index++) {
    if (items[index] === target) {
      return index;
    }
  }
  return -1;
}
What It Enables

It lets you quickly find any item in a list, no matter how messy or unordered it is.

Real Life Example

Finding a friend's name in a list of contacts on your phone when you don't know if the list is sorted.

Key Takeaways

Linear search checks items one by one until it finds the target.

It works on any list, sorted or not.

It's simple but can be slow for very large lists.