1

Let's say I have the following code:

function check(code){
    var result=false;
    $.each(arrayOfFunctions,function(){
        thisresult=this.call(this,code);
        if (thisresult==true){
            result=true;
        }
    });
    return result;
}

So I have a function with one input. I have an array of functions that I apply to that data. If any of them are true, the outer function is true.

When I'm in the inner function, is there a way to return on the outer function? Are there any other optimizations that can be done to my code?

1
  • 1
    You may want to optimize the anonymous function to function() { return !(result = this.call(this, code)); } Commented Feb 10, 2012 at 21:06

1 Answer 1

3

In jQuery, using return false inside $.each and $().each will stop the loop. Before stopping the loop, set a variable which will be returned.

function check(code){
    var result = false;
    $.each(arrayOfFunctions,function(){
        thisresult = this.call(this,code);
        if (thisresult == true){
            result=true;
            return false; // = similar to the "break" keyword in a loop
        }
    });
    return result;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Good point, I actually have that in my code, but I omitted it here to reduce confusion.
@Joe Considering the names and formatting, I assumed that you provided pseudo-code. If that's your real code, you should at least prefix thisresult by var. If you share more information about your code, I can optimize it. I suspect that you don't even need jQuery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.