Node.js Module Code explanation? Path.js trim(arr) { }

I'm trying to learn JavaScript better, and while reviewing Node.js Module source I came across this nested function in the Path.js module.

I've basically determined that it's used to do some sort of "cleanup" of the array paths but still just can't 'GRASP' what it's really doing... can anyone explain this?

Here is the link to the module: https://github.com/joyent/node/blob/master/lib/path.js

function trim(arr) {
      var start = 0;
      for (; start < arr.length; start++) {
        if (arr[start] !== '') break;
      }

      var end = arr.length - 1;
      for (; end >= 0; end--) {
        if (arr[end] !== '') break;
      }

      if (start > end) return [];
      return arr.slice(start, end - start + 1);
    }

This is embedded within the "export.relative" function for posix version.

If anyone can help me understand this, it might ease my mind a little bit...

What this function does is that it removes empty string values from the beginning and the end of the given array. If you call trim(['', '', 1, 2, '']), you get [1, 2].

It starts by checking for empty string values from the beginning first (from the index of 0). Then it does the same check but starting from the end (from the index of arr.length-1 which is the last index in the array) and going backwards.

The checking stops when a non-empty-string value is encountered.

If start > end then there are no non-empty-string values and it is thus safe to return an empty array.

If there are some array elements that should be preserved (like 1 and 2 in my example), the array is just trimmed by its slice method. The slice method corresponds to the String::substr method for instance.

I hope you understand now.