Skip to content
Advertisement

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

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:

JavaScript

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

JavaScript

It returns the correct value. Why is this?

Advertisement

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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement