Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda