0
0
DSA Javascriptprogramming~15 mins

Linear Search Algorithm in DSA Javascript - Build from Scratch

Choose your learning style9 modes available
Linear Search Algorithm
📖 Scenario: You are helping a librarian find a specific book in a shelf. The shelf is a list of book titles. You will write a program to search for a book title by checking each book one by one until you find it.
🎯 Goal: Build a simple linear search program that looks for a given book title in a list of books and tells if it is found or not.
📋 What You'll Learn
Create an array called books with exact titles: 'The Hobbit', '1984', 'Pride and Prejudice', 'To Kill a Mockingbird', 'The Great Gatsby'
Create a variable called searchTitle with the exact value '1984'
Use a for loop with variable index to go through books
Inside the loop, use an if statement to check if books[index] equals searchTitle
Create a variable called found set to false before the loop and set it to true when the book is found
After the loop, print 'Found' if found is true, otherwise print 'Not Found'
💡 Why This Matters
🌍 Real World
Searching for an item in a list is a common task, like finding a book on a shelf or a contact in a phone.
💼 Career
Understanding linear search helps in many programming jobs where you need to find data without special indexing or sorting.
Progress0 / 4 steps
1
Create the list of books
Create an array called books with these exact titles: 'The Hobbit', '1984', 'Pride and Prejudice', 'To Kill a Mockingbird', 'The Great Gatsby'
DSA Javascript
Hint

Use square brackets [] to create an array and separate titles with commas.

2
Set the book title to search
Create a variable called searchTitle and set it to the string '1984'
DSA Javascript
Hint

Use const to create a variable and assign the exact string.

3
Search for the book using a loop
Create a variable called found and set it to false. Then use a for loop with variable index to go through books. Inside the loop, use an if statement to check if books[index] equals searchTitle. If yes, set found to true and use break to stop the loop.
DSA Javascript
Hint

Remember to initialize found before the loop. Use break to stop once found.

4
Print the search result
After the loop, use console.log to print 'Found' if found is true, otherwise print 'Not Found'
DSA Javascript
Hint

Use an if statement to check found and print the correct message.