This was my first thought as well. If he instead initializes:
var result = "";
and checks for: if (result.length === 0) {
...
in the third conditional, is there still a bug?