In Javascript, what's better than try/catch for exiting an outer scope?
<p>In Javascript, I sometimes want to return a value from a scope that <em>isn't</em> 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 outer function should just exit. Unfortunately, I can't think of a simpler way to do this than by hacking try/catch for the purpose:</p>

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

<p>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?</p>

<p>Edit: since the answers to date are variations of "ew that's bad
you're not supposed to do that", let me add some necessary
context. I'm hacking on an open-source compiler that targets
Javascript. <em>No one is going to write this code by hand</em>, so please
don't tell me "this is a bad programming technique". What I want is a
better <em>code generation</em> technique. The question is whether anyone has
any clever hack for exploiting Javascript to get more flexible control
transfer.</p>

<p>The reason assigning the result to a local variable and checking it is
ruled out is because that requires understanding the code in a way
that is hard for a compiler to do.</p>
