OneBite.Dev - Coding blog in a bite size

search for a specific element in an array in Javascript

Code snippet on how to search for a specific element in an array in Javascript

  function searchElement(arr, element) {
  
    //Loop through each item in the array
    for (let i = 0; i < arr.length; i++) {
    
      //When element is found, return its index
      if (arr[i] === element) {
        return i;
      }
    }
    
    //Return -1 when element is not found
    return -1;
  }

This code searches for a specific element in an array using a for loop. First, we define the function searchElement, which takes an array and the element we want to search for as parameters. It then uses a for loop to go through each element in the array and check if it is equal to the element we are looking for. If the element is found, it will return the index of it. If the element is not found, the loop will finish and the function will return -1.

javascript