In Javascript, what's better than try/catch for exiting an outer scope?

Posted by gruseom on Stack Overflow See other posts from Stack Overflow or by gruseom
Published on 2010-04-09T17:24:20Z Indexed on 2010/04/09 17:43 UTC
Read the original article Hit count: 191

Filed under:

In Javascript, I sometimes want to return a value from a scope that isn't the current function. It might be a block of code within the function, or it might be an enclosing function as in the following example, which uses a local function to recursively search for something. As soon as it finds a solution, the search is done and the whole thing should just return. Unfortunately, I can't think of a simpler way to do this than by hacking try/catch for the purpose:

function solve(searchSpace) {
    var search = function (stuff) {
        solution = isItSolved(stuff);
        if (solution) {
            throw solution;
        } else {
            search(narrowThisWay(stuff));
            search(narrowThatWay(stuff));
        };
    };
    try {
        return search(searchSpace);
    } catch (solution) {
        return solution;
    };
};

I realize one could assign the solution to a local variable and then check it before making another recursive call, but my question is specifically about transfer of control. Is there a better way than the above? Perhaps involving label/break?

© Stack Overflow or respective owner

Related posts about JavaScript