Home > Blockchain >  How to use an object outside of scope of a loop in javascript
How to use an object outside of scope of a loop in javascript

Time:02-12

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.

CodePudding user response:

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());

CodePudding user response:

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!

  • Related