Searching for the closest "stop" elements surrounding a start point This code works but is there a simple / better way to do this?

It starts from a particular point (starthere) in the array, looks for first stop value to the left of start point, and the first stop to the right side.

Basically returns the closest values' positions to a start point both sides. (I'll make this a function.)

var arr = ['f','f','stop','stop','f','f','starthere','f','f','f','stop','stop','f','f','f','f'];

var i = arr.indexOf('starthere');
while (i--) {
    if (arr[i] == 'stop') {
        document.write(i + '&lt;/br&gt;');
        break;
    }
}

for (var i = arr.indexOf('starthere'); i &lt; arr.length; i++) {
    if (arr[i] == 'stop') {
        document.write(i);
        break;
    }

}


Returns 3&lt;/br&gt;10
There is an overload of .indexOf that takes a second parameter indicating the starting location for the search.  That can be used to find the stop after starthere. Then you can use .slice to grab the part of the array before starthere with lastIndexOf to find the stop that comes before:

var i = arr.indexOf('starthere');
var stopafter = arr.indexOf('stop', i);
var stopbefore = arr.slice(0, i).lastIndexOf('stop');
document.write(stopbefore + '&lt;/br&gt;' + stopafter);