Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
Creating a function to search for a value in an array and return it's position index using a loop

I'm very new to JavaScript. I'm trying to create a function that can two take two arguments, an array and a value. The function should return the index where the value is found but ff the value is not found, it should return -1. I want to this using a loop and not a method like for example indexOf.

So this is what I got by now:

function getIndex(arr, value) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === value) {
      return i;
    } else {
      return -1;
    }
  }
}

For some reason it keeps returning -1 even if the value if found. What am I doing wrong?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

In the first time your if happen you return no matter what!

If arr[i] == value you return the index, else - you return -1.

What you want to do is return -1 in the case that none of the array elements is found.

function getIndex(arr, value) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === value) {
      return i;
    }
  }
  return -1;
}
about 4 years ago · Juan Pablo Isaza Report

0

Your logic is wrong here. First, you return -1 when the function fails to search the right value. Thus, the function is paused and no longer executing. You can learn more about the return statement at MDN. To solve this problem, you need to put the return statement outside the loop. Here is the working code:

<script>
function getIndex(arr, value){
for(let i =0; i<arr.length; i++){
if(arr[i] === value){
return i;
}
}
return -1;
}
document.write(getIndex([1,2,3,4], 21));
</script>

The reason why this piece of code works is because when the value is found, it returns the positions where the value is. Thus, terminates the function. But if it is not, the loop will go forever until I is less than arr.length. Once I is less than arr.length, the loop is done and the return statement is executed.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!