Why can I not set the value of a variable outside a JavaScript while loop?

Tags: ,



I’m trying to work through a binary challenge and it requires setting a midway point between the start and end of an array.

This is the code:

function binary (val, nums) {
  var start = nums[0];
  var end = nums.length -1;
  var found = false;
  var mid = Math.floor((start + end)/2);
  var position = -1;

  while(!found && start <= end) {
    if (nums[mid] === val) {
        found = true;
        position = mid;  
    }
    else if (nums[mid] > val) {
       end = mid -1;

    }
    else {
        start = mid + 1;
    }
  }
return position;
}

console.log(binarySearch(12, [1,2,3,4,5,6,7,12]))

The console returns nothing but the function doesn’t stop either. However, if I declare var mid outside the loop and then set the value within the loop like so

var mid;

while(!found && start <= end) {
    mid = Math.floor((start+end)/2)
    if (nums[mid] === val) {
        found = true;
        position = mid;  
    }
    else if (nums[mid] > val) {
       end = mid -1;

    }
    else {
        start = mid + 1;
    }
}

It returns the correct value. Why is this?

Answer

In the first code snippet (outside while loop), you are never changing mid value where as in second code snippet, you are updating mid in each iteration based on start and end values and hence the difference in result.



Source: stackoverflow