[SOLVED] Creating a function to search for a value in an array and return it's position index using a loop

Issue

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?

Solution

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;
}

Answered By – Omri Attiya

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.