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

205
Vistas
How to use an object outside of scope of a loop in javascript

The following function compares a value against an array and goes through the elements of the array until finds an element that is smaller than the comparison value. As a result it should return the index of that element where condition was met. In this example it should return the index of 4 (with value of 5). I store this index in lowestNumberIndex but can only access it within the scope of last if() function. How can I access it outside the for loop? Notice that I have initiated the object outside of the for loop.

function findLowerIndex () {

  let firstArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  let compareValue = [6];

  var lowerNumber = null;
  var lowestNumberIndex = null;

  for (i=firstArray.length-1; i>0; i--) {
    lowerNumber = firstArray[i];
    if (lowerNumber < compareValue) {
      lowestNumberIndex = i;
      return;
    }
  }
}
  • In case you are wondering, I need to have the for loop in reverse format because this is part of a larger code and the dataset is organized in a way that doing it backwards ensures efficiency of run.
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You could take the index for looping and as result. For the comparing value use the value without wrapping it in an array.

function findLowerIndex() {
    const
        firstArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
        compareValue = 6;

    let index = firstArray.length;

    while (index--) {
        if (firstArray[index] < compareValue) break;
    }
    // use the found index
    return index;
}

console.log(findLowerIndex());

about 4 years ago · Juan Pablo Isaza Denunciar

0

So thanks to all the comments and solutions I figured what the problem was. The problem was that I did not know using return jumps you out of the whole function. Using break instead worked!

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