Implementing Linear Search in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will delve into the topic of JavaScript programming and explore various concepts related to it. Through this lab, you will gain hands-on experience in coding and learn how to implement various algorithms and techniques in JavaScript. By the end of this lab, you will have a better understanding of JavaScript programming and be able to apply your skills to real-world applications.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") subgraph Lab Skills javascript/variables -.-> lab-28470{{"`Implementing Linear Search in JavaScript`"}} javascript/data_types -.-> lab-28470{{"`Implementing Linear Search in JavaScript`"}} javascript/arith_ops -.-> lab-28470{{"`Implementing Linear Search in JavaScript`"}} javascript/comp_ops -.-> lab-28470{{"`Implementing Linear Search in JavaScript`"}} javascript/cond_stmts -.-> lab-28470{{"`Implementing Linear Search in JavaScript`"}} javascript/loops -.-> lab-28470{{"`Implementing Linear Search in JavaScript`"}} javascript/array_methods -.-> lab-28470{{"`Implementing Linear Search in JavaScript`"}} end

To practice coding, open the Terminal or SSH and type node. The linear search algorithm finds the first index of a given element in an array.

Here's how it works:

  • Use a for...in loop to iterate over the indexes of the given array.
  • Check if the element in the corresponding index is equal to item.
  • If the element is found, return the index. Use the unary + operator to convert it from a string to a number.
  • If the element is not found after iterating over the whole array, return -1.

Here's the code:

const linearSearch = (arr, item) => {
  for (const i in arr) {
    if (arr[i] === item) return +i;
  }
  return -1;
};

To test the function, call it with an array and a value to search for:

linearSearch([2, 9, 9], 9); // 1
linearSearch([2, 9, 9], 7); // -1

Summary

Congratulations! You have completed the Linear Search lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like