You're checking for a null local variable value in the third conditional, but appending to that same variable in the first two, which would either cause a runtime error in most languages or never pass the third conditional.
var result = "";
and checks for: if (result.length === 0) {
...
in the third conditional, is there still a bug?